Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Forked from marushu/set-filter-by-tax.php
Last active July 14, 2021 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhowellsmead/6d1653ca14fc77dd1b59aa8cd3c8af00 to your computer and use it in GitHub Desktop.
Save markhowellsmead/6d1653ca14fc77dd1b59aa8cd3c8af00 to your computer and use it in GitHub Desktop.
Supports multiple filters.
<?php
add_action('restrict_manage_posts', [$this, 'taxonomyFilter']);
add_filter('parse_query', [$this, 'filterByTaxonomy']);
public function taxonomyFilter()
{
global $typenow;
$args = [
'public' => true,
'_builtin' => true
];
$custom_post_types = get_post_types($args);
$custom_post_types = array_values($custom_post_types);
if (empty($typenow) || in_array($typenow, $custom_post_types) === true) {
return;
}
$taxonomies = get_object_taxonomies($typenow);
$post_type = $this->post_type;
if ($typenow == $post_type) {
foreach ($taxonomies as $tax) {
if (! empty($tax) && ! is_wp_error($tax)) {
$selected = isset($_GET[ $tax ]) ? $_GET[ $tax ] : '';
$info_taxonomy = get_taxonomy($tax);
wp_dropdown_categories([
'show_option_all' => $info_taxonomy->labels->archives,
'taxonomy' => $tax,
'name' => $tax,
'orderby' => 'name',
'selected' => $selected,
'show_count' => false,
'hide_empty' => true
]);
}
}
}
}
public function filterByTaxonomy($query)
{
global $pagenow, $typenow;
$taxonomies = get_object_taxonomies($typenow);
$post_type = $query->query['post_type'];
if (! empty($taxonomies) && ! is_wp_error($taxonomies)) {
foreach ($taxonomies as $tax) {
if (! empty($tax)) {
$q_vars = &$query->query_vars;
if ($pagenow == 'edit.php'
&& isset($q_vars[ 'post_type' ])
&& $q_vars[ 'post_type' ] == $post_type
&& isset($q_vars[ $tax ])
&& is_numeric($q_vars[ $tax ])
&& $q_vars[ $tax ] != 0
) {
$term = get_term_by('id', $q_vars[ $tax ], $tax);
$q_vars[ $tax ] = $term->slug;
}
}
}
}
}
@markhowellsmead
Copy link
Author

Make sure that query_var isn't set to false in register_taxonomy.

@murdokland
Copy link

Hi,
the link after sorting is like edit.php?s&post_status=all&post_type=equipe etc.. and display empty results.
If i remove the s& manually it's works fine.
any idea how to correct that?
thanks

@markhowellsmead
Copy link
Author

No, that's Core technology. s is the search parameter; it should be s=& if there is no search term.

@murdokland
Copy link

thanks for the reply but it's strange I doesn't changed the code, and after filtering the url become like
edit.php?s&post_status=all&post_type=equipe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment