Filter a View of child posts by two parent posts in different post relationships

This example will show you how to use the wpv_filter_query API and shortcode attributes to extend a View’s Query Filter capabilities to support two post relationship filters. You want to create a list of child posts filtered by two different parent post types, but the View editor GUI will only let you add one post relationship Query Filter. Let’s assume the child post type is “Footnotes” and the parent post types are “Books” and “Lessons”. You know the Book ID and the Lesson ID, and you would like to find the child Footnotes that belongs to both parents. Add the following code to your child theme’s functions.php file:

// Filter a View of child posts by two parents in different post relationships
add_filter( 'wpv_filter_query', 'query_two_rels_by_shortcode_atts',99,3 );
function query_two_rels_by_shortcode_atts( $query_args, $views_settings, $view_id) {
  global $WP_Views;

  // comma-separated list of view IDs where you want to apply this filter
  $view_ids = array( 12345 );

  // if in the right view
  if (in_array($view_id, $view_ids)){
    $shortcode_atts = array('bookid'=>0, 'lessonid'=>0);
    $viewSlug = get_post_field('post_name', $view_id);
    // find the shortcode attributes for this view
    foreach($WP_Views->view_shortcode_attributes as $atts) {
      if($atts['name'] == $viewSlug) {
        $shortcode_atts = $atts;
        break;
      }
    }

    // add toolset_relationships arguments to the query using the parent post IDs
    $book_id = $shortcode_atts['bookid'];
    $lesson_id = $shortcode_atts['lessonid'];
    $query_args['toolset_relationships'] = array(
      array(
        'role' => 'child',
        'related_to' => $book_id,
        'relationship' => 'book-footnote',
      ),
      array(
        'role' => 'child',
        'related_to' => $lesson_id,
        'relationship' => 'lesson-footnote',
      ),
    );
  }
  return $query_args;
}

Change 12345 to match the View’s numeric ID, and remove any post relationship Query Filters from the View editor. Then insert the View shortcode and add the parent post IDs like this:

[wpv-view name="your-view-slug" bookid="345" lessonid="678"]

Ticket reference: https://toolset.com/forums/topic/filtering-view-based-on-relationship-with-two-parents/


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