1

I struggling to find a way to count and conditionally apply // do stuff based upon the number of terms of a specific taxonomy(ABC) in archive.php...

All I have is this below but it counts all the terms across the site. I want it to only count the number of different terms on the archive.php and apply a conditional based upon the count.

<?php echo 'There are ' . wp_count_terms( 'state', array( 'hide_empty' => false ) ) . ' terms in the taxonomy state.'; ?>
6
  • This should help: wordpress.stackexchange.com/questions/27116/… You can also dig through the following global $wp_query; var_dump($wp_query); You'll find everything you need in there. the pre_get_posts action and $query->set() function could also help with you goal, I think.
    – admcfajn
    Jan 4 '18 at 2:59
  • That above link is counting posts, I need to count terms.
    – Pete
    Jan 4 '18 at 3:54
  • You have to look at each post to see what terms are associated and count all the unique ones you find.
    – Milo
    Jan 4 '18 at 4:09
  • Thanks, unfortunately my coding skills are very basic and I wouldn't know what to do with it all. Thanks anyway.
    – Pete
    Jan 4 '18 at 4:35
  • I don't think there's a "silver-bullet" function for this one. First, you'd determine the taxonomies being displayed, then you can count the terms of those taxonomies... Possibly just the assigned terms? this is where I'm lost with your question... Do you just want to count all terms of a given taxonomy? Or count only the number of terms displayed on a given page of the archive? For example, page one of the archive has 10 different terms and page 2 has 5 different terms? Are you using one taxonomy or multiple? If you could elaborate a bit that would help.
    – admcfajn
    Jan 4 '18 at 17:44
0

This should do the trick.

<?php 
// start with an empty array
$all_term = array();
if ( have_posts() ) {
    // loop through all posts, this could go outside of the main loop or be part of it, if placing outside the main loop be sure to reset the loop or namespace your queries
    while ( have_posts() ) {
        the_post(); 
        // add the list of terms for a given taxonomy to the $all_term array
        array_push($all_term, wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "ids")));
    } // end while
} // end if

// remove duplicates from the $all_term array
$all_term = array_unique($all_term, SORT_REGULAR);
// output the result
echo count($all_term);
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.