首页 > 解决方案 > 仅在“pre_get_posts”钩子中查询带有特色图片的帖子

问题描述

我使用钩子“pre_get_posts”只查询在首页有特色图片的帖子:

add_action( 'pre_get_posts', 'my_pre_get_posts' );
function my_pre_get_posts( $q ){ 

    if (    $q->is_home()       // only target homepage
         && $q->is_main_query() // only target the main query
         && !is_admin()         // target front end only
    ) {
        $q->set( 'meta_key', array( '_thumbnail_id' ) );
    }
}

看起来这部分被忽略了。

$q->set( 'meta_key', array( '_thumbnail_id' ) );

感谢您的帮助。

标签: wordpresswordpress-themingcustom-wordpress-pageswordpress-thesis-theme

解决方案


您需要检查 '_thumbnail_id' meta_key 是否存在。所以让我们像这样修改你的代码。

add_action( 'pre_get_posts', 'my_pre_get_posts' );
 function my_pre_get_posts( $q ){ 
  if (    $q->is_home()       // only target homepage
     && $q->is_main_query() // only target the main query
     && !is_admin()         // target front end only
  ) {
         $meta_query = array(
             array(
                'key'=>'_thumbnail_id',
                'compare'=>'EXISTS',
             ),
         );
         $query->set('meta_query',$meta_query);
  }
 }

推荐阅读