Question

I know how to get all of the Wordpress terms, but I need a "filtered" down version of the results. Is it possible to get all of the terms that are in the result of a Wordpress query? I have this query here:

<?php
   $args=array(
  'post_type' => 'gw_activity',
  'post_status' => 'publish',
  'orderby' => 'date',
  'meta_query' => array(
     'relation' => 'AND',
      array(
         'key' => 'activity_category',
         'value' => 'mindful_life',
         'compare' => '='
      )
   ), 
  'posts_per_page' => 10
);
$my_query = null; 
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { 
 $all_terms = array();
  while ($my_query->have_posts()) : $my_query->the_post(); ?>      
  <?php $terms = wp_get_post_terms( $my_query->post->ID, array( 'gw_activity_tag' ) ); ?>
  <?php       
        foreach ( $terms as $term ) {
            $all_terms[] = $term->name;
        }        
  ?>                                            
  <?php endwhile; }
  wp_reset_query();
?>
<!-- End Custom Query -->
<?php
    $unique_terms = array_unique( $all_terms ); 
    $result = array_unique($unique_terms);
    foreach ($result as $value) {
        echo $value . '<br />';
    }

?>

But I can't figure how to run the query & put a "Where" clause in it, like you can with MySQL. Any help / suggestion or even point me in the right direction would be greatly appreciated. I'm stuck

Was it helpful?

Solution

Check this function: wp_get_post_terms()

Assuming your post supports two taxonomies called tax_a and tax_b, you can try something like this, exactly where you wrote your comment:

<?php $terms = wp_get_post_terms( $query->post->ID, array( 'tax_a', 'tax_b' ) ); ?>

<?php foreach ( $terms as $term ) : ?>
    <p><?php echo $term->taxonomy; ?>: <?php echo $term->name; ?></p>
<?php endforeach; ?>

This will print all the terms for each post retrieved by the query.


EDIT

If what you want is all the terms in all the posts retrieved by the query, you can store the values in an array and then use a function like array_unique(), like this:

$all_terms = array();
foreach ( $terms as $term ) {
    $all_terms[] = $term->name;
}

// ... and outside the WHILE loop
$result = array_unique( $all_terms );
foreach ( $result as $term ) {
    echo $term . '<br/>;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top