Filter a View of child posts by parent post status, where the parent is not private

In this example, we have a one-to-many post-relationship between two custom post types, and we want to set up a View of child posts. Since some parent posts are private, we do not want to show their children. Set up a View of child posts with no post-relationship filter. Then use this code snippet to filter out all private parents’ children from the results.

/* --------------------------------------------------------------------------------- */
// FILTER A VIEW OF CHILD POSTS BY PARENT POST STATUS NOT EQUAL TO PRIVATE
// This filter can be applied to any View of child posts to filter out
// children of private parent posts.
// ---------------------------------------------------------------------------------
add_filter('wpv_filter_query', 'ts_parent_not_private_func', 10, 3);
function ts_parent_not_private_func($query, $view_settings, $view_id) {
  $views = array( 12345 ); // only filter these views
  if( in_array( $view_id, $views ) ) {
    $child_ids = array(); // we will push IDs here if the parent is not found, or private
    $children_args = array(
      'post_type' => 'child-type-slug',
      'posts_per_page' => '-1',
      'post_status' => 'publish',
      // you may want to add more filters here to improve the performance of this query
    );
    $children = new WP_Query($children_args);
    foreach( $children->posts as $child ){
      $parent = toolset_get_related_post( $child, 'relationship-slug', 'parent' );
      // if there is no parent or the parent is private, push this ID into the exclusion array
      if( !$parent || get_post_status($parent) == 'private' ){
        array_push( $child_ids, $child->ID );
      }
    }

    $query['post__not_in'] = isset( $query['post__not_in'] ) ? $query['post__not_in'] : array();
    $query['post__not_in'] = array_merge($query['post__not_in'], $child_ids );
  }
  return $query;
}

Replace 12345 with the numeric ID of your View of child posts, or a comma-separated list of numeric View IDs if you want to apply this filter to more than one View. Replace child-type-slug with the slug of the child post type, and replace ‘relationship-slug’ with the slug of the post-relationship. Consider adding more criteria to the child post query to improve the performance of this filter if a large number of child posts exist.


Support Thread Example

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments