Okay yes, that makes sense. This type of filter isn't built in to Views, but I can show you how to use two Views together and a small code snippet to make this work. It's a bit complicated but I will be able to walk you through it and help if you get stuck.
- Create a View of Department posts, filtered by your M2M relationship, and configure the Query Filter to select posts that are related to the post where this View is shown.
- In the Loop Output editor, insert a shortcode to display the post IDs of the Department posts, separated by a comma. Here's a snippet you can use as the contents of your Loop:
[wpv-layout-start][wpv-items-found]<!-- wpv-loop-start --><wpv-loop>[wpv-item index=1][wpv-post-id][wpv-item index=other],[wpv-post-id]</wpv-loop><!-- wpv-loop-end -->[/wpv-items-found][wpv-no-items-found]<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>[/wpv-no-items-found][wpv-layout-end]
- Insert the View of Department posts in the Single Staff Member Content Template or Template Layout. You should see a comma-separated list of the IDs of all the Departments related to the current Staff Member.
- Insert this code snippet in your child theme's functions.php file:
add_filter( 'wpv_filter_wpv_view_shortcode_output', 'ts_clean_view_output', 5, 2 );
function ts_clean_view_output( $out, $id ) {
$ids = array( 12345 );
if ( in_array( $id, $ids )) {
$start = strpos( $out, '<!-- wpv-loop-start -->' );
if (
$start !== false
&& strrpos( $out, '<!-- wpv-loop-end -->', $start ) !== false
) {
$start = $start + strlen( '<!-- wpv-loop-start -->' );
$out = substr( $out , $start );
$end = strrpos( $out, '<!-- wpv-loop-end -->' );
$out = substr( $out, 0, $end );
} else {
$start = strpos( $out, '>' );
if ( $start !== false) {
$out = substr( $out, $start + 1 );
$end = strpos( $out, '<' );
$out = trim(substr( $out, 0, $end ));
}
}
}
return $out;
}
- Replace 12345 with the numeric ID of your View of Department posts.
- Create a new View of Staff Members, filtered by the M2M relationship, where the relationship is set using a shortcode attribute "wpvrelatedto".
- In the Loop editor, insert a post link shortcode to display a link to each Staff Member's single post.
- Insert the View of Staff Members on the Staff Members Content Template or Template Layout. Move the shortcode for the View of Departments into the wpvrelatedto shortcode attribute for the View of Staff Members, like this:
[wpv-view name="view-of-staff-members" wpvrelatedto="[wpv-view name='view-of-departments']"]
- Now your View of Staff Members is filtered by the list of Department IDs related to the current Staff Member.