the_meter413
the_meter413

Reputation: 299

How can I summate an ACF field value for each post on an archive page?

I have a custom post type that I created with ACF with a True/False field type called complete. On my archive page for the CPT, I want to display text along the lines of "X of Y complete."

I can solve the Y part with $the_count = $GLOBALS['wp_query']->found_posts; but I'm unsure how to solve my X part.

How do I grab the value of complete from each post that appears on my archive page?

Upvotes: 0

Views: 170

Answers (1)

the_meter413
the_meter413

Reputation: 299

After some (more) googling, I found this solution on the ACF plugin site, and then modified it to meet my needs. I came up with the code below to create a shortcode to add a count of all posts on the archive page where complete = 1:

add_shortcode('archive_number_complete', 'add_archive_number_complete');

function add_archive_number_complete() {
    // define the args for the custom query 
    $args = array(
        'post_type' => 'objective',
        'fields' => 'ids',
        'meta_query' => array(
            array(
                'key' => 'complete',
                'value' => 1,
            ),
        ),
    );
    
    // The Query
    $the_query = new WP_Query( $args );

    // Counting the results
    $the_count = count($the_query->posts);
    
    //* Restore original Post Data
    wp_reset_postdata();
        
    return $the_count;
}

Upvotes: 0

Related Questions