WordPressWriting
May 4, 2016
2 min read

WordPress Lessons: WP_Query Shenanigans

WordPress is Awesome! There is absolutely no doubt about that. But as with so many things, even the best of things have some very silly…

WordPress is Awesome! There is absolutely no doubt about that. But as with so many things, even the best of things have some very silly…

WordPress Lessons: WP_Query Shenanigans

WordPress is Awesome! There is absolutely no doubt about that. But as with so many things, even the best of things have some very silly problems. One such problem I have experienced is with WP_Query ignoring the post_status parameter if we were to use it in conjunction with tag parameter.

The code I was working to begin with was something like this:

$terms = wp_get_post_terms( $post_ID, 'post_tag', array( 'fields' => 'ids' ) );
 
$args = array(
	'tag__in'         => $terms,
	'post_type'       => 'custom_post_type',
	'post__not_in'    => array( $post_ID ),
	'suppress_filters' => false,
);
 
$myquery = new WP_Query( $args );

Upon executing the above code, I realized that the post_type parameter was completely ignored and every post was returned that matched the filters. This issue left me perplexed for a while.

Fortunately, for me, WordPress has provided us all with a precious collection of filters that can help us in situations like these. The filter that helped me out in this case was the posts_where filter.

Initially, I created a simple function

public function posts_where( $where ) {
	$where .= " AND wp_posts.post_type = 'sponsors'";
	return $where;
}

and then modified my code to look as follows

add_filter( 'posts_where', array( $this, 'posts_where' ) );
 
$terms = wp_get_post_terms( $post_ID, 'post_tag', array( 'fields' => 'ids' ) );
 
$args = array(
	'tag__in'         => $terms,
	'post_type'       => 'sponsors',
	'post__not_in'    => array( $post_ID ),
	'suppress_filters' => false,
);
 
$myquery = new WP_Query( $args );
 
// --- application logic ---
 
remove_filter( 'posts_where', 'posts_where' );
wp_reset_postdata();

Adding a remove filter ensured that my custom where clause added to the WP_Query played nicely with other queries and did not interfere with anything else.

By Ajitem Sahasrabuddhe on May 4, 2016.

Share this research

code