I have been reading the WP_Query Codex looking for a way to loop through all the posts that have the post format ‘video’ OR ‘image’, within a given category.
If this wasn’t enough, this category is given by a variable $catslug
(I need it to be this way).
I have only found ways of looping through one of the following
-
image OR video
-
image AND category
-
video AND category,
but what I need is more complex, something like this:
post-format-image
AND $catslug
) OR (post-format-video
AND $catslug
)
Is it possible to do a tax_query
within a tax_query
?
Something like this:
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array($catslug)
),
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-image' )
)
),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array($catslug)
),
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-video' )
)
)
)
);
$query = new WP_Query( $args );
Anyone knows any workaround or a hack to get this?
Perhaps I’m just thinking the wrong way.
This actually a good question. The simple answer here is that you cannot use multiple
tax_query
‘s.This had me quickly testing the following scenario before I left for work. Just for fun I went and tried to make use of the category parameters with a
tax_query
, but that gave me posts from the desired category and posts that also belongs to both post formatsI came up with a possible solution, unfortunately I cannot test this right now.
Here is my line of though here:
As you need random results, I would suggest that you add your post formats into an array
You now are going to use
shuffle
to shuffle the array, and then take the first entry from that array, which will be either video of image, and use that in yourtax_query
.This way you will get posts that is in your desired category and in either video or image post format.