How to filter by custom relationship field
-
Heres the code I used to add a dropdown menu to filter posts (custom post type made with pods) by custom fields.
add_action( 'restrict_manage_posts', 'acs_admin_posts_filter_restrict_manage_posts' ); function acs_admin_posts_filter_restrict_manage_posts(){ $type = 'POST-TYPE'; $filter_meta_key = 'META-KEY-NAME'; if (isset($_GET['post_type'])) { $type = $_GET['post_type']; } //only add filter to post type you want if ('snp_genotype' == $type){ //change this to the list of values you want to show //in 'label' => 'value' format $values = array( 'label1' => 'value1', 'label2' => 'value2' ); ?> <select name="<?php echo $filter_meta_key; ?>"> <option value=""><?php _e('Filter By ', 'acs'); ?></option> <?php $current_v = isset($_GET[$filter_meta_key])? $_GET[$filter_meta_key]:''; foreach ($values as $label => $value) { printf ( '<option value="%s"%s>%s</option>', $value, $value == $current_v? ' selected="selected"':'', $label ); } ?> </select> <?php } } add_filter( 'parse_query', 'acs_posts_filter' ); function acs_posts_filter( $query ){ global $pagenow; $filter_meta_key = 'META-KEY-NAME'; if (isset($_GET['post_type'])) { $type = $_GET['post_type']; } if ( is_admin() && $pagenow=='edit.php' && isset($_GET[$filter_meta_key]) && $_GET[$filter_meta_key] != '') { $query->query_vars['meta_key'] = $filter_meta_key; $query->query_vars['meta_value'] = $_GET[$filter_meta_key]; } }
It works for regular custom fields but I can’t get it to work for relationship fields (fields which relate the custom post type to another custom post type). Lets say my custom post type is called paintings and the relationship field is called artists (as in the artist the painted the painting), if I wanna select only paintings which are painted by Picasso (lets say his ID is 5) what do I need to set the meta_key and meta_value to? For example, if I do:
$query->query_vars['meta_key'] = 'artist'; $query->query_vars['meta_value'] = 'Picasso';
or
$query->query_vars['meta_key'] = 'artist'; $query->query_vars['meta_value'] = 5;
Neither work. I also tried
$query->query_vars['meta_key'] = 'artist.id'; $query->query_vars['meta_value'] = 5;
but that doesn’t work either. Is there a way to do this?
- The topic ‘How to filter by custom relationship field’ is closed to new replies.