I need to output the name of the custom post type within archive.php and single.php.

I would use something like this:

if ( 'staff' == get_post_type() ) {

$post_type = 'staff';


echo '<div class="'.$post_type.'">Content</div>';

This would give me the required result of <div class="staff">

However, it appears I can also access the global variable called $post_type and simply output this on archive.php or single.php even without declaring global, for example this archives the same result as above:

<div class="<?php echo $post_type; ?>">

Codex says the global variable $post_type is for use within the Wordpress admin area.

My questions are:

  1. Why does $post_type work without declaring it globally first?
  2. Is it a good idea to use the $post_type global var as demonstrated above for use in theme templates?

Thank you

  • Does it work when you are logged out too?
    – Luckyfella
    Commented Jul 23, 2017 at 20:08
  • It's the same behaviour logged in or logged out.
    – Dave
    Commented Jul 23, 2017 at 20:55

1 Answer 1


The global $post_type is usually from the public query variable of the main query $wp_query, but get_post_type() is the post type of the current $post object, within the loop.

So for e.g. secondary loops this can be different.

The global $post_type might not always be set, as the default post type for WP_Query is the post post type.

From WP::register_globals() we can see how the post_type query variable becomes globally accessible:

// Extract updated query vars back into global namespace.
foreach ( (array) $wp_query->query_vars as $key => $value ) {
    $GLOBALS[ $key ] = $value;

as I posted in my recent answer here.

In general I would use the WordPress API calls, instead of using direct globals, as the former usually is designed to handle various cases, including defaults, and is updated when needed.

Working directly with the globals increases the risk of overriding them.

If your goal is to setup some CSS selectors, one can often just use the ones provided for the <body> tag, with the body_class() core function. Also consider the post_class() core function, within your loop, as it already contains the post type class info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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