Display only posts with thumbnail using WP_Query

You need to define your arguments before you pass them to WP_Query, not after. Also, your meta_query should be an array of an array, not just an array This $query = new WP_Query($thumbs); $thumbs = array( ‘meta_query’ => array(‘key’ => ‘_thumbnail_id’) ); should look like this $thumbs = array( ‘meta_query’ => array( array( ‘key’ => … Read more

How to trigger 404 for custom query var?

There is an action specifically for this: function my_parse_query( $wp_query ) { if ( $wp_query->get( ‘my_custom_var’ ) > 42 ) { $wp_query->set_404(); status_header( 404 ); } } add_action( ‘parse_query’, ‘my_parse_query’ ); That should load the 404.php template in your theme, if you have it. Otherwise, it will fall back to index.php. This will also trigger … Read more

modifying meta_query on parse_query

Right after the pre_get_posts hook is fired, the public meta_query attribute of WP_Query is overridden with: $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $q ); where $q = &$this->query_vars; $q = $this->fill_query_vars($q); So I don’t think it will work to modify this attribute, like you’re trying to do, before the pre_get_posts hook is activated. Instead we need … Read more

“pre_get_posts” firing on every query

Basically what you are looking for is the global $wp_the_query variable which is set to the value of the main query. It may not be a perfect fit for 100% of cases but will probably work fine in 99% of cases: add_action( ‘pre_get_posts’, ‘custom_post_count’ ); function custom_post_count( $query ){ global $wp_the_query; if ( $wp_the_query === … Read more

Problem with ‘post__not_in’

You are trying to supply an array as part of the string query parameter. You could instead just supply the arguments list as an array like this: $newQuery = new WP_Query( array( ‘posts_per_page’ => 5, ‘orderby’ => ‘rand’, ‘cat’ => $cats[0]->term_id, ‘post__not_in’ => array($exclude_post) ) );

WP_Query by Category Name

category is a valid parameter for get_posts, not for WP_Query. Here are the valid category parameters for WP_Query cat (int) – use category id. category_name (string)– use category slug (NOT name). category__and (array) – use category id. category__in (array) – use category id. category__not_in (array) – use category id. You can use either use cat … Read more

Is ‘no_found_rows’ a silver bullet for WP_Query optimization when getting all posts of a certain type?

Your code will run five SQL queries in total. When setting no_found_rows => true the first two queries SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.ID IN (1,49,63,249,72,95,259,207,183,225) AND wp_posts.post_type=”post” AND (wp_posts.post_status=”publish”) ORDER BY wp_posts.post_date ASC LIMIT 0, 10 SELECT FOUND_ROWS() will become a single query like SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND … Read more