Fill the exclude array() in get_posts()

I'm using this code to populate the dropdown menu in a meta box.

        $parents = get_posts(
           array(
           'post_type'   = 'jhk_story', 
           'orderby'     = 'ID', 
           'order'       = 'ASC', 
           'numberposts' = -1,
           'exclude'     = array(121, 131, 138),
           )
        );

This post_type contains the parents of a post_type 'jhk_frames', which are the only child. So, the children contain in their post_parent field the post_ID of their parent. The parent contains in their post_parent field still the default zero.

My question is: how do I select only the posts in the post_type 'jhk_story' that have a child?

Next step is to put the id's of these posts in the 'exclude' array. The values you see right now are put there by me, just for example (and a check that is works).

Any help will be appreciated greatly.

Topic get-posts wp-query posts Wordpress

Category Web


After three days of struggling and posting a question here I managed to find an answer. Yeh I know... To my defense I can say that it's my first WP project. I did it this way:

    $exclude = get_excluded_parents();

    $parents = get_posts(
        array(
            'post_type'   => 'jhk_story', 
            'orderby'     => 'ID', 
            'order'       => 'ASC', 
            'numberposts' => -1,
            'exclude'     => $exclude,
        )
    );

    The rest of the code here ...

  }

} // story_frame_attributes_meta_box()


/* 
 * Filters excluded parents from post_type: story_frame
 */
function  get_excluded_parents() {

  // Select all posts with post_type = story_frame
  $childs = get_posts (
    array (
      'post_type'   => 'story_frame',
      'orderby'     => 'ID',
      'order'       => 'ASC',
      'numberposts' => -1
    )
  );

  $exclude = array();

  foreach ( $childs as $child ) {

    if ( 0 < $child->post_parent ) {

      array_push( $exclude, $child->post_parent );

    }

  } // foreach $child

  return $exclude;

} // get_excluded_parents()

Hope someone will benefit from it.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.