WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am wondering if it is possible to return a list of all the "tags" that are associated with ALL returned posts. In theory, I would then use this list of terms to build appropriate "filter by" links for refining the search.

For instance: A user searches for "Foo" and there are 100 results. Would it be possible to get a collection of all the posts' tags? So, post "Foo 1" might be tagged "little bar" and post "Foo 2" might be tagged, "big bar" and "foo foo", etc and etc.

I would like to do this before the while_posts() is doing its thing. Failing that, I think I could use the while_posts() loop to collect all the tags for each post. This is the most obvious solution to me, except that then the list isn't where I want it in the markup. AND, I'm not sure how to include tags on page 2 (and onward) of the results.

share|improve this question
up vote 0 down vote accepted

The global $wp_query object is available before you call have_posts(). All you have to do is running through this object’s posts member with get_the_terms().

Sample function:

function get_query_terms( $taxonomy = 'post_tag' )
    $list = array ();

    foreach ( $GLOBALS['wp_query']->posts as $id )
        if ( $terms = get_the_terms( $id, $taxonomy ) )
            foreach ( $terms as $term )
                $list[ $term->term_taxonomy_id ] = $term;

    ksort( $list );

    return $list;

Be aware any usage of query_posts() might break this list.

share|improve this answer
Perfect. Thanks @toscho. I never use query_posts so that shouldn't be a major restriction. – helgatheviking Dec 23 '12 at 21:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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