Adding the numerical values from a custom field from all posts in a category

We have various options for achieving this, but I want you to start with the categories since WordPress does not allow a post without a category, which means we won’t miss a post from the following query.

Let’s say, you have created a meta using the custom fields to save an accumulated number for each post. (Alternatively: Could use ACF or any other plugin features).

enter image description here

We can access the number of a post with the following inbuilt WP function:

get_post_meta($post_id, 'hours', true);

Since you don’t want to make it call on every page load, you could create a cron job and call it on a timely basis, and save the totals. I think saving the number in the options table is fine for this purpose:

function accumulation_save() {

    $total = 0;
    $options = array();
    
    // Get all the categories
    $cats = get_categories();

    // Run through the each categories
    foreach ($cats as $key => $cat) {
        $subtotal = 0;

        // Grab posts from a category
        $the_query = new WP_Query(array('cat' => $cat->term_id));
        if ( $the_query->have_posts() ) {
            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                $subtotal += (int)get_post_meta(get_the_ID(), 'hours', true);
                $options[get_the_title()] = get_post_meta(get_the_ID(), 'hours', true);
            }
        }
        $total += $subtotal;
        $options[$cat->name] = $subtotal;
        wp_reset_postdata();
    }
    $options["Build total"] = $total;

    update_option('accumulation', $options);
}

Here you can find a detailed explanation of how to create the cron job.

And we have to print it as:

function accumulation_print() {

    $options = get_option('accumulation');

    foreach ($options as $key => $value) {
        echo "$key : $value hrs<br>";
    }
}

PS: If you are assigned a post in multiple categories, the totals will add up.

tech