Filtering admin view of CPT by Relationship to another CPT
Support › MB Relationships › Filtering admin view of CPT by Relationship to another CPT
- This topic has 2 replies, 2 voices, and was last updated 7 months, 3 weeks ago by
Peter.
-
AuthorPosts
-
September 7, 2024 at 1:48 AM #46351
Christopher Alvarez
ParticipantI'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:
- Testing on archive page (non-admin) using just the MB_Relationships_API::get_connected() function, but that's returning nothing as well.
- Checking the relationship ID (multiple times... it works to display related info in the main app, but not through the query or API.
- Using a WP_query() instead of the MB API
Is it a timing issue? Why would the API call fail? Is there another way to do this?
`
September 7, 2024 at 3:46 AM #46352Christopher Alvarez
ParticipantOk, 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; }
September 9, 2024 at 11:33 PM #46388Peter
ModeratorHello 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? -
AuthorPosts
- You must be logged in to reply to this topic.