WordPress特定分类下single.php查询语句修改需求及现有代码
问题分析与修正方案
你的代码有几个关键问题,导致没法实现需求:
- 条件判断错了:你要改的是
single.php(文章详情页)的查询,但代码里用了is_category()(判断是否是分类归档页),而且$query->in_category()是错误用法——in_category()是针对单篇文章的函数,不能直接调用$query的这个方法。 - 获取文章ID的方式错了:
the_ID()会直接输出当前文章ID,不能作为get_post_meta的参数,得用get_the_ID()来返回ID值。 - 排序参数无效:
orderby和order的参数写的是'orderby'和'order',这俩是无效值,得改成合法规则,比如用'post__in'来按你给定的ID顺序排序。 - meta_query写法冗余:数组里的
'0'键不需要特意声明,而且用NOT EXISTS比较时,不需要加value参数。 - 钩子触发场景不对:
single.php的主查询默认是获取当前打开的文章,如果你要替换主查询展示posts_ids里的文章列表,得调整判断条件;如果只是要在详情页里加个自定义列表,那根本不用pre_get_posts钩子。
修正后的代码(修改主查询场景)
如果你的需求是:当当前打开的文章属于cat-name分类时,替换single.php的主查询,展示posts_ids字段里指定的文章列表,用下面的代码:
function target_my_category_query( $query ) { // 条件:非后台环境、是主查询、当前是文章详情页、当前文章属于目标分类 if ( !is_admin() && $query->is_main_query() && $query->is_single() ) { $current_post_id = get_the_ID(); if ( in_category( 'cat-name', $current_post_id ) ) { $postIds = get_post_meta( $current_post_id, 'posts_ids', true ); $arrayIds = !empty($postIds) ? explode( ',', $postIds ) : array(); if ( !empty($arrayIds) ) { $query->set( 'post_type', 'post' ); $query->set( 'post__in', $arrayIds ); // 按post__in给定的ID顺序排序 $query->set( 'orderby', 'post__in' ); $query->set( 'order', 'ASC' ); $query->set( 'post__not_in', get_option('sticky_posts') ); $query->set( 'meta_query', array( array( 'key' => 'cfvna', 'compare' => 'NOT EXISTS' ) ) ); } } } } add_action( 'pre_get_posts', 'target_my_category_query' );
补充:自定义查询场景(更常用)
如果你只是想在single.php里单独加一个模块,展示posts_ids里的文章,不需要修改主查询,直接在single.php的对应位置加这段代码就行:
if ( in_category( 'cat-name' ) ) { $postIds = get_post_meta( get_the_ID(), 'posts_ids', true ); $arrayIds = !empty($postIds) ? explode( ',', $postIds ) : array(); if ( !empty($arrayIds) ) { $custom_query = new WP_Query( array( 'post_type' => 'post', 'post__in' => $arrayIds, 'orderby' => 'post__in', 'order' => 'ASC', 'post__not_in' => get_option('sticky_posts'), 'meta_query' => array( array( 'key' => 'cfvna', 'compare' => 'NOT EXISTS' ) ) ) ); // 循环输出文章 if ( $custom_query->have_posts() ) { while ( $custom_query->have_posts() ) { $custom_query->the_post(); // 这里写你的文章模板代码,比如the_title(), the_content()等 } wp_reset_postdata(); } } }
内容的提问来源于stack exchange,提问作者bpy
相关产品推荐
相关产品推荐

