Support Forum
Support › MB Relationships › Filtering admin view of CPT by Relationship to another CPT
I'd like to filter the list of "episodes" in the admin edit view so that only episodes related to a selected "show" are returned. I set the filter up, and am passing the show ID in as a parameter, but the query is coming back with zero results.
Here's the code:
add_action( 'pre_get_posts', 'filter_episodes_by_selected_show' );
function filter_episodes_by_selected_show($query) {
global $pagenow, $typenow;
if ($typenow == 'episodes' && is_admin() && $pagenow == 'edit.php' && isset($_GET['filter_show']) && $_GET['filter_show'] != '') {
$show_id = intval($_GET['filter_show']);
// Query for episodes related to the selected show via MetaBox
$meta_query = array(
array(
'key' => 'episodes-to-shows',
'value' => $show_id,
'compare' => '='
)
);
$query->set('meta_query', $meta_query);
}
}
What am I doing wrong? I've tried a few things aleady:
Is it a timing issue? Why would the API call fail? Is there another way to do this?
`
Ok, I took a slightly different approach and it appears to be working (filtering the episodes to only those related to the selected show), but the "Show" column is empty.
add_action( 'parse_query', 'filter_episodes_by_selected_show' );
function filter_episodes_by_selected_show($query) {
global $pagenow, $typenow;
if ($typenow == 'episodes' && is_admin() && $pagenow == 'edit.php' && isset($_GET['filter_show']) && $_GET['filter_show'] != '') {
$show_id = intval($_GET['filter_show']);
if (!empty($show_id)) {
$query->set('relationship', [
'id' => 'episodes-to-shows',
'to' => $show_id
]);
}
}
return $query;
}
Hello Christopher,
Do you mean to display the "Show" post in a column of the table list? Please enable the admin column feature when registering the relationship, following the documentation https://docs.metabox.io/extensions/mb-relationships/#using-meta-box-builder
If not, can you please share some screenshots of the issue on your site?