I have a new WP_Query
that I use to generate a custom loop and display a set of posts. One of the things the query does is provide pagination.
Before I display the queried posts though, I’d like to get a list of all the tags for the posts found. I know I can do this by looping through each of the posts and then removing duplicates, but I was hoping for a more elegant approach.
I don’t think that is possible. The SQL query performed by
WP_Query
returns only the post objects (and perhaps some metadata), while the tags resides in a different table. When looping through the returned posts in templates you usually putthe_tags();
or something similar in your templates, which in turns runs a new database query for each post.However, you could run a separate query to load the tags prior to running your primary posts query. As far as I know there is no function WordPress API that will let you load the tags of more than one post at the time, but you could accomplish that by directly calling
$wpdb
.Something like this might help get you started:
As you can see this assumes that you know your post IDs beforehand, which you most likely does not. In that case you would need to replace the lists in the parentheses with a subquery, which in it’s simplest form would be
SELECT ID FROM $wpdb->posts
, but more likely will need to filter/order/limit posts by category, date, etc. A problem I encountered is that my version of MySQL did not supportLIMIT
in subqueries. If yours doesn’t either it might be hard to accomplish this in one query. Unless you have a lot of posts you could just loop through yourWP_Query
first and collect the post IDs. In any case, this will be faster than running separate queries for each post since you will only run one tag-related query instead of running one for each post.For the sake of posterity, I ended up just iterating through the loop twice: once to get the tags, and then to actually display the page.
Here’s my code:
Getting the tags of multiple posts can be achieved by passing
'object_ids'
toget_terms()
.First, let another
WP_Query
return you only the IDs of your desired posts. For example get all posts of a given category:Now that you have the IDs you can simply hand them over to
get_terms()
and will be returned a list of all tags of these selected posts:Source: https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#comment-2500