首页 > 解决方案 > 从自定义帖子类型中获取兄弟姐妹

问题描述

我已经设置了一个具有以下结构的自定义帖子类型:

我有两个名为“Vrouwen”和“Mannen”的主要帖子当我访问其中一个主要帖子时,我只想显示兄弟姐妹。

我坚持实现这一目标。

但随后“孩子”也被显示出来。我需要以某种方式更深一层。

感谢所有帮助!

我尝试了下面的代码。

$mysibling        = $post->post_parent;
$mychild          = $post->ID;
$mychildmysibling = array( $mychild, $mysibling );

$args = array(
    'post_parent'    => $mychildmysibling,
    'post__not_in' => array( $post->ID ),
    'posts_per_page' => -1,
    'post_type'       => 'collectie'
);

$parent = new WP_Query( $args );
while ( $parent->have_posts() ) : $parent->the_post();

但随后“孩子”也被显示出来。我需要以某种方式更深一层。

标签: phpwordpress

解决方案


首先post_parent需要一个数字,但您设置了一个数组。其次,您基本上需要使其仅适用于主页?所以查询应该是这样的:

// find children for the main post
$children = get_children( array('post_parent' => $post->ID));

// check if the post has any children
if ( ! empty($children) ) {
   // get all posts where the parent is set as children to main post
   $args = array(
        'post_parent__in' => array_keys($children),
        'posts_per_page' => -1,
        'post_type' => 'collectie'
    );

   $siblings = new WP_Query( $args );

   if ( $siblings->have_posts() ) {
       while ( $siblings->have_posts() ) {
           $siblings->the_post();

           echo get_the_title();
       }
   }

   wp_reset_postdata();
}

推荐阅读