Trying to highlight custom taxonomy pages in the main nav, so I am trying to get the post_type of the current rendered page (to compare to the menu item):

add_filter('nav_menu_css_class', 'current_tax_nav_class', 10, 2);
function current_tax_nav_class($classes, $item) {
    $post_type = get_query_var('post_type');

    echo ">>>";
    print_r( $post_type );
    echo "<<<";

    return $classes;

But cannot get post_type var to return anything. This code is in functions.php

Using WP Version 4.4.1

  • Are you trying to get the post_type of the element you are about to render in a menu? – yivi Jan 17 '16 at 8:34
  • I'm trying to get the post_type of the current displayed page – keeg Jan 17 '16 at 8:36
  • Does the answer below help? – yivi Jan 17 '16 at 10:36

If you are trying to get the post type for the current 'post', I think you could go with get_post_type().

Like this:

$post_type = get_post_type();

Try it out.

| improve this answer | |
  • I think it would be better: get_post_type( get_queried_object() ); Other than that, get_post_type() function works in the filter, I've tested it. – cybmeta Jan 17 '16 at 12:18
  • So that works... sort of... It works on pages, but when I'm on an archive page of a taxonomy it only returns if the taxonomy has posts associated with it, which means that if taxonomy has nothing, the post_type returns empty... – keeg Jan 18 '16 at 3:02
  • Well, that would be correct, right? A taxonomy doesn't necessary have a post_type associated. What post type would you want returned on an empty taxonomy? – yivi Jan 18 '16 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.