How I can change the condition or compare operator for WP_Query in pre_get_posts

So here is my problem
I want to show Posts if have same category if not have post then show post of same tag. And to do that I am using “pre_get_posts” action. and setting query like following.

function related_custom_posts($query){
   $query->set( 'category__in', array(2,3) );
   $query->set( 'tag__in', array(10,13) );
}

add_action( 'pre_get_posts', 'related_custom_posts', 1 );

But it create sql like this
AND ( wp_term_relationships.term_taxonomy_id IN (2) AND tt1.term_taxonomy_id IN (11) ) but i need this with OR condition AND ( wp_term_relationships.term_taxonomy_id IN (2) OR tt1.term_taxonomy_id IN (11) )

Thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can achieve the OR relation using the tax_query argument like so:

$query->set( 'tax_query', array(
    'relation' => 'OR',
    array(
        'taxonomy' => 'category',
        'terms'    => array( 2, 3 ),
    ),
    array(
        'taxonomy' => 'post_tag',
        'terms'    => array( 10, 13 ),
    ),
) );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x