WordPress: How to find the post type of the current page in wp-admin

December 19, 2012

Finding the post type of a current page in the WordPress wp-admin area can be a pain in the butt, particularly if you need to check from the edit page. After a while of pounding my head on the keyboard I finally stumbled across the correct WordPress hook. If you are attempting to do this you need to be inside the ‘admin_head’ action. Here is some code that may be of use.

// Setup the hook
add_action('admin_head', 'do_stuff_with_post_type' );

function do_stuff_with_post_type() {
    // Get the post type
    $post_type = get_current_post_type();

    if( '...' == $post_type ) {
        // do some stuff
    }
}

function get_current_post_type() {
        global $post, $typenow, $current_screen;

        // Check to see if a post object exists
        if ($post && $post->post_type)
            return $post->post_type;

        // Check if the current type is set
        elseif ($typenow)
            return $typenow;

        // Check to see if the current screen is set
        elseif ($current_screen && $current_screen->post_type)
            return $current_screen->post_type;

        // Finally make a last ditch effort to check the URL query for type
        elseif (isset($_REQUEST['post_type']))
            return sanitize_key($_REQUEST['post_type']);

        return null;
    }