Get post type on edit page


I am writing the backend for my theme and have 4 custom post types. I have registered them all and now I am writing the metaboxes and handlers.

My question is: in WordPress admin, is there a way of determining which custom post type you’re editing? i.e. lets say I have a custom post type of Testimonials, I click Add New and am presented with various fields. Is there a function in WordPress that will tell me what this post type is?

I’ve tried get_post_type(), but it returns nothing.

in progress 0
Steve Clark 12 years 2010-12-23T05:45:00-05:00 0 Answer 86 views 0

Answer ( 1 )


    There are hooks and variables set that will allow you determine post type pretty easily, so you can hook onto actions specific to a given type, i’m going to provide some examples below.


    If wanted to add a metabox to the post creation screen for the book post type, then i’d probably use a hook along the lines of..

    add_action( 'add_meta_boxes_book', 'my_callback_defining_metaboxes' );
    function my_callback_defining_metaboxes() {
        add_meta_box( ... );

    You can replace book with an appropriate post type, eg. post, page, or a custom one.

    If i wanted to enqueue scripts onto the edit or add new posts screen for the book post type, i might use..

    add_action( 'admin_print_scripts-edit.php', 'my_func_to_enqueue_scripts' );
    add_action( 'admin_print_scripts-post-new.php', 'my_func_to_enqueue_scripts' );
    function my_func_to_enqueue_scripts() {
        global $typenow;
        if( 'book' == $typenow )
            wp_enqueue_script( ... );

    If i wanted to go a step further and hook onto every page that deals with the book post type i’ll use a more generic hook and perform conditional logic on one of the admin variables..(as long as you don’t hook in really early you can reference these vars reliably).

    add_action( 'admin_print_scripts', 'enqueue_scripts_on_specific_posttype_pages' );
    function enqueue_scripts_on_specific_posttype_pages() {
        global $parent_file;
        if( 'edit.php?post_type=book' == $parent_file )
            wp_enqueue_script( ... );

    $parent_file is always the link or URL of the parent menu item for the given post type, which you’ll notice is different to the generic $hook_suffix that’s appended to the admin_print_scripts- hook, eg. admin_print_scripts-edit.php ..

    The above example would hook the enqueue onto any page for the book post type, that includes the taxonomy management screens.

    Hope the above is helpful.

Leave an answer