• Hello,

    I have a blog that records a time in hours for each post. This value is stored in a custom field called ‘session_duration’.

    I am trying to sum all those values to get a total value. I’d like to store this function in the functions.php file with a shortcode so that I can call the total hours from a post or page.

    Here is my current code:

    function total_hours (){
            $total_hours=0;
            $meta_key = 'session_duration';//set this to your custom field meta key
            $allhours=$wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
            foreach ($allhours as $hours) {
                    $total_hours = $total_hours + $hours;
            }
            echo 'Total hours are '.$total_hours;
    }
    add_shortcode('total_hours','total_hours');

    However this causes multiple errors. If I remove this code from the function and place it by itself it works. I’m a total newbie to php having only started working with it in the last week or so. Any help is appreciated.

Viewing 10 replies - 16 through 25 (of 25 total)
  • anonymized-13749270

    (@anonymized-13749270)

    Well, the code works perfect, but the only issue is in the data stored in meta keys.

    Is this legal for you 2.5 ( hours ) ?

    Well, as the variable dumping didn’t show the entire string content, try this

    foreach ( $hours as $hour )
        	$sum .= $hour. ', ';
    return $sum;

    And use a pastebin to provide the output.

    You might want to look at the first function where you store data in meta keys, see if there’s anything wrong.. I suspect that, using those fields, there is a duplication on insert, so the insert is twice ( look into your PHPMYADMIN postmeta table, search for %session_duration% meta_key

    You could delete all existing data, or set new meta_key ( like session_duration_test for debugging ) and see how it goes..

    Thread Starter plbarrett2004

    (@plbarrett2004)

    Ok, I made some progress. I should have recognized the problem was on the input earlier. I was using a plugin called Custom Fields. If I used the built in wordpress custom fields, it now works, or at least it is outputting the proper array of numbers.

    Previously every edit was appending a new entry to the array.

    I’ll post results in a bit after I play some more.

    Much appreciate your help!!!!

    anonymized-13749270

    (@anonymized-13749270)

    Glad to hear you are making progress πŸ™‚

    Yes, only couple tests can get you to what you want, and don’t forget to keep me posted over here πŸ™‚

    You are very welcome !!

    Thread Starter plbarrett2004

    (@plbarrett2004)

    Ok, so the problem was definitely the plugin. By using the default custom field entry ‘shop_hours’ in posts, I am able to get the appropriate behavior. The total is working properly. I finally cleaned up my code, and my next thought is to implement the same code by category. I don’t think I can use the current select statement to do so though… any thoughts?

    /*
    The following functions will be used to total all session hours by post
    using the custom field 'shop_hours'
    Subsequent functions will work for specific categories.
    */
    
    // Function totals all session hours
    function total_hours() {
        global $wpdb;
        $total_hours=0;
        $meta_key = 'shop_hours';//set this to your custom field meta key
        $allhours=$wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
        foreach ($allhours as $hours) {
                $total_hours = $total_hours + $hours;
        }
        return $total_hours;
    }
    
    // Total of all hours by category
    // Total hours for empennage (cat id = 3)
    function emp_hours() {
        global $wpdb;
        $emp_hours=0;
        $meta_key = 'shop_hours';//set this to your custom field meta key
        $allhours=$wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
        foreach ($allhours as $hours) {
            $emp_hours = $emp_hours + $hours;
        }
        return $emp_hours;
    }
    
    // Shortcodes for all hour total functions
    add_shortcode('total-hours','total_hours'); // Total
    add_shortcode('emp-hours','emp_hours'); // Empennage (cat id = 3)
    Thread Starter plbarrett2004

    (@plbarrett2004)

    Digging a little further into this, the wp_postmeta table does not have a column for the category, so I’d need to do more than one statement to first select only posts from that category…

    anonymized-13749270

    (@anonymized-13749270)

    Hi Peter,

    So, the function for category thing is the following:

    function emp_hours() {
        global $wpdb;
        $emp_hours=0;
        $meta_key = 'shop_hours';//set this to your custom field meta key
        $allhours=$wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
        foreach ($allhours as $hours) {
            $emp_hours = $emp_hours + $hours;
        }
        return $emp_hours;
    }

    Which counts sum data for entire posts, and, you want it to count hours for only total posts listed under a specific category you know its ID? is that the deal?

    Regards,

    Samuel.

    Thread Starter plbarrett2004

    (@plbarrett2004)

    Yes that’s correct. The category ID for the example is 3.

    anonymized-13749270

    (@anonymized-13749270)

    Hi Peter,

    Can you give this a try:

    function emp_hours( $atts ) {
    
    	$a = shortcode_atts( array(
            'category' => ''
        ), $atts );
    	global $wpdb;
    	$emp_hours = 0;
    	$cat = "{$a['category']}";
    	if ( $cat == '' ) {
    		return 'Please set a category ID';
    		return;
    	}
    	$results = $wpdb->get_results( "SELECT meta_value,post_id FROM $wpdb->postmeta WHERE meta_key = 'shop_hours'" );
    	foreach ( $results as $item ) {
    		$id = $item->post_id;
    		$val = $item->meta_value;
    		$categories = get_the_category($id);
    		foreach ( $categories as $category ) {
    			$emp_hours += ( $category->cat_ID == $cat ) ? $val : '';
    		}
    	}
    	return $emp_hours;
    
    }
    add_shortcode('emp-hours','emp_hours');

    And test this shortcode:
    [emp-hours category=”3″]

    Let me know how it goes.

    Samuel

    Thread Starter plbarrett2004

    (@plbarrett2004)

    Samuel,

    That works like a charm. Nice touch being able to pass the category id to the function via the short code! That makes building the site the way I want a snap. I’ve used this and a few other tweaks to build my index page dynamically in the format I want. This has been on my to-do list for months.

    You’ve been a HUGE help. Thank you!!

    Cheers,
    Peter

    anonymized-13749270

    (@anonymized-13749270)

    Hi Peter,

    I am glad that it did work, and that this is no longer in your to-do list of the project πŸ™‚

    You are welcome. Good luck with the rest of the work you are doing and have a nice day !

Viewing 10 replies - 16 through 25 (of 25 total)

The topic ‘Adding function to sum values in custom field’ is closed to new replies.