如何过滤查询以仅显示来自父类别的帖子?

时间:2016-12-01 作者:jrcollins

我正在使用Mini Loops plugin 显示最近的帖子。查看父类别时,它会显示该类别以及任何子类别中的帖子。我想更改此设置,以便只显示分配给父类别的帖子。

在查看了插件的文档之后,我认为可以使用过滤器来修改插件的输出,但我不确定具体如何操作。

文档中给出了以下函数,作为基于标记修改查询的示例:

/*
Modify the query args before they are run
Can either work on all instances, or only some by checking existing args

This demo changes the \'tag__in\' query to \'tag__and\' to limit the number of matching posts
*/
add_filter( \'miniloops_query\' , \'miniloops_query_filter_test\' );
function miniloops_query_filter_test( $query ) {
    if ( $query[\'tag__in\'] == array( 53, 82 ) ) {
        $query[\'tag__and\'] = $query[\'tag__in\'];
        unset( $query[\'tag__in\'] );
    }
    return $query;
}
函数修改查询参数,但如果该参数不存在,是否可以添加该参数,而不只是修改?不确定这是否可能。

UPDATE:我在下面添加了插件文件中的相关代码部分:

$tax_query = array();

foreach( array_keys( $taxes ) as $k => $slug ) {

    //original code is this single commented line, if you need to revert

    //$tax_query[] = array( \'taxonomy\' => $slug, \'field\' => \'id\', \'terms\' => explode( \',\', $taxes[ $slug ] ) );



    $oper = \'IN\';

    $ids = explode( \',\', $taxes[ $slug ] );

    if ( count( $ids ) == 1 && $ids[\'0\'] < 0 ) {

        //if there is only one id given, and it\'s negative

        //let\'s treat it as \'posts not in\'

        $ids[\'0\'] = $ids[\'0\'] * -1;

        $oper = \'NOT IN\';

    }

    $tax_query[] = array(

        \'taxonomy\' => $slug,

        \'field\'    => \'id\',

        \'terms\'    => $ids,

        \'operator\' => $oper );

}
我尝试添加include_children => FALSE 但它没有起作用。

1 个回复
最合适的回答,由SO网友:jrcollins 整理而成

我终于能够使用插件提供的过滤器来实现这一点。查询使用[cat] 获取不支持include_children 参数因此,我必须定义tax_query 取消设置前的参数[cat].

功能如下:

add_filter( \'miniloops_query\' , \'miniloops_child_posts_filter\' );
function miniloops_child_posts_filter( $query ) {
$query[\'tax_query\'] = array( array(
  \'taxonomy\' => \'category\',
  \'field\'    => \'term_id\',
  \'terms\'    => $query[\'cat\'],
  \'include_children\' => 0,
),);
unset($query[\'cat\']);
return $query;
}

相关推荐