I am trying to add a filter to the admin edit screen for a custom post type called "trip" that I set up using Custom Post Types plugin. I'd like the filter to filter by the custom field added by ACF, "trip_status". Please see the image below for reference.
I am using the code below to set this up (modified from here), however every time I try to filter by the options in the dropdown I have created, I get a response "Invalid Post Type" from Wordpress.
/** Create the filter dropdown */
add_action( 'restrict_manage_posts',
'atg_admin_trips_filter_restrict_manage_posts' );
function atg_admin_trips_filter_restrict_manage_posts($query){
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if ('trip' == $type){
$values = array(
'Quality Check' => 'Quality Check',
'Pending Approval' => 'Pending Approval',
'Pay Deposit' => 'Pay Deposit',
'Deposit Paid' => 'Deposit Paid',
'Collecting Names' => 'Collecting Names'
);
?>
<select name="tripstatus">
<option value=""><?php _e('Filter By ', 'wose45436'); ?></option>
<?php
$current_v = isset($_GET['tripstatus'])?$_GET['tripstatus']:'';
foreach ($values as $label => $value) {
printf
(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
}
?>
</select>
<?php
}
}
/** Filter by post meta -> trip_status */
add_filter( 'pre_get_posts', 'atg_trips_posts_filter' );
function atg_trips_posts_filter( $query ){
global $pagenow;
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if( 'trip' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['tripstatus']) && $_GET['tripstatus'] != '') {
$value = $_GET['tripstatus'];
$query->query_vars['meta_key'] = 'trip_status';
$query->query_vars['meta_value'] = $value;
}
}
Any input anyone could offer as to why this is not working would be greatly appreciated. I now the issue is related to setting the query vars, but not sure what I'm doing wrong as I've verified the meta_key in the database is 'trip_status'.
This is the url output when I try to 'filter' the posts: http://localhost/BOOKINGSITE/wp-admin/edit.php?s=&post_status=all&post_type=trip&_wpnonce=f51f34525b&_wp_http_referer=%2FBOOKINGSITE%2Fwp-admin%2Fedit.php%3Fs%26post_status%3Dall%26post_type%3Dtrip%26action%3D-1%26m%3D0%26tripstatus%26filter_action%3DFilter%26paged%3D1%26action2%3D-1&action=-1&m=0&tripstatus=Quality+Check&filter_action=Filter&paged=1&action2=-1
Also, if anyone can provide insight into the difference between using parse_query versus pre_get_posts in this instance, or the difference between: 1- $query->query_vars['meta_key'] = 'trip_status'; 2- $query->set('meta_key', 'trip_status');