使用WP_QUERY打印类别的直系后代

时间:2013-11-02 作者:blake

因此,我很难在页面上只打印类别的直接子级。这是我的代码:

 $category_id = get_cat_ID(\'destinations\');
 $args = array(\'child_of\'   => $category_id);
 $categories = get_categories($args);
 $args = array (
    \'category__and\'                    => $categories->$cat_ID
);
   $recent_posts = new WP_Query($args);
if ($recent_posts->have_posts())  : while ($recent_posts->have_posts()) : $recent_posts->the_post();
此代码打印每个类别,而不管父类别是谁。如果我更改此选项:

$最近发布的帖子=新的WP\\U查询(\'cat=43\');它打印出正确的类别,但也打印出所有的儿童和儿童的儿童(显然)。我只想把直接相关的孩子们打印出来。我继续重复了一个serialize($categories),它返回了正确的数组。但是,当我在第二次声明之后序列化($args)时,它会给出:

a:1:{s:13:"category__and";N;}
这确实很奇怪。为什么它会返回$类别->$cat\\U ID的“N”?我一整天都在尝试这样做,但都没有成功。我也试着找到另一种方法来做我想做的事,但什么也没想到。

有什么想法吗?

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

From the Codex:

 child_of 
    (integer) Display all categories that are descendants (i.e. children & grandchildren) of the category identified by its ID. There is no default for this parameter. If the parameter is used, the hide_empty parameter is set to false. 
和

parent  
    (integer) Display only categories that are direct descendants (i.e. children only) of the category identified by its ID. This does NOT work like the \'child_of\' parameter. There is no default for this parameter. [In 2.8.4]
因此,首先,如果您只需要立即的decentant,那么您使用的参数是错误的。您需要:

$args = array(\'parent\'   => $category_id);
其次,get_categories 将为您提供一个对象数组,因此您需要这样的内容来提取ID。

$cats = wp_list_pluck($categories,\'cat_ID\');
$args = array (
  \'category__and\'                    => $cats
);
为您提供:

$category_id = get_cat_ID(\'destinations\');
$args = array(\'parent\'   => $category_id);
$categories = get_categories($args);
$cats = wp_list_pluck($categories,\'cat_ID\');
$args = array (
  \'category__and\'                    => $cats
);
$recent_posts = new WP_Query($args);

结束