0

I have a function that checks page specific and global settings to determine a class related to sidebars. I call the function from the archive.php template and try to check that post_type is 'post', however the post_type var isn't set.

Relevant Code:

function get_sidebar_class() {
    global $wp_query;
    echo 'Post type: ' . get_query_var( 'post_type' );
    echo '<pre>' . print_r( $wp_query->query_vars, true ) . '</pre>';
}

post_type comes back empty for both attempts. Why isn't it set? Other variables (E.g. category) are set, but not post_type.

2

Query vars are... fun like that. Depending on which archive you are messing with get_post_type() just might be simple enough to do it (it gets type from actual post, not query).

Otherwise you might want to go for get_queried_object() to figure out what precisely you are dealing with.

  • will get post type work on an archive page? – GusRuss89 Feb 10 '14 at 21:34
  • @GusRuss89 yes, but note that it will get type from the post (not query), which is usually same for all posts in archive, but depends on your specifics. – Rarst Feb 10 '14 at 21:41
  • Thanks, I think that should suffice for now. I don't intend to mix post types on the archives for now. A sidebar widget or something listing custom post types wouldn't mess with it would it? – GusRuss89 Feb 10 '14 at 21:43
  • @GusRuss89 it should be fine as long as secondary queries are properly reset. – Rarst Feb 10 '14 at 21:50
1

What type of page/post are you looking at when you echo this out? post_type does not get populated when looking at a post or post archive. Try on Pages and see if you see post_type at that point.

I believe post_type is populated on anything EXCEPT posts, and perhaps pages - Pages doesn't have an archive, so it may just have a page property storing an ID or slug, etc. Therefore, essentially it's only used for custom post types.

  • @Eric_Holmes I'm just trying to make sure it's not a custom post type basically, so I guess I could check if post_type is empty AND pagename is empty (page isn't set on archive pages and post_type isn't set on pages), it just feels like it's not as solid a solution as it could be... – GusRuss89 Feb 10 '14 at 21:55
0

Am alternate way of getting query vars is $wp_query->get( 'post_type' ) ;. If post_type is set, you can retrieve it that way.

  • Since get_query_var() wraps exactly this it won't help in this case. – Rarst Feb 10 '14 at 18:18

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.