1

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.

1 Answer 1

0

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.

1
  • Perfect. Thanks @toscho. I never use query_posts so that shouldn't be a major restriction. Commented Dec 23, 2012 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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