Skip to main content
1 of 2
RoseCoder
  • 181
  • 2
  • 3
  • 18

Custom Taxonomy Filter Issues

I have a custom post type with a few custom taxonomies and I am using a piece of code to filter the posts based on the taxonomy on the main edit page using drop-down menus, which works great, but I have found that when I click onto a taxonomy's main page, and click on the number of posts that contains a specific term, it says 'trying to get property of non-object' and does not filter them. This is the code that is causing me issues:

function taxonomy_filter_post_type_request( $query ) {
  global $pagenow, $typenow;

  if ( 'edit.php' == $pagenow ) {
    $filters = get_object_taxonomies( $typenow );
      foreach ( $filters as $tax_slug ) {
        $var = &$query->query_vars[$tax_slug];
          if ( isset( $var ) ) {
           $term = get_term_by( 'id', $var, $tax_slug );
            if($var){
             $var = $term->slug;
           }
        }
     }
  }
}

add_filter( 'parse_query', 'taxonomy_filter_post_type_request' );

The line that reads $var = $term->slug; seems to be causing the problem, But if i replace:

if($var){
  $var = $term->slug;
}

to:

is_array($var){
  $var = $term->slug;
}

Then it works when I click on the number of posts that contain a certain term, but the drop-down menu filters fail to work.

By looking at this, is it possible to make them both work?

RoseCoder
  • 181
  • 2
  • 3
  • 18