Get post type with get_post_type()

Hi, I’m learning about WordPress. I am trying to get the post type with get_post_type() but in “All Pages” page, I can’t get the post type. In “All Posts” it works, but in “All Pages” it is not working. Could give me some please give me some advice?

Here is the code I am using.

add_action( ‘admin_notices’, ‘test’:wink:;

function test(){

$post_type_page = get_post_type();

echo $post_type_page;

}

  • Oguz
    • Recruit

    Hey leoventans ,

    Hope you are doing fine today!

    According to function page at WordPress.org, get_post_type uses global $post object. When you visit Posts page global $post object is the latest post. But when you visit Pages, global $post object is NULL. So that’s why there is nothing when you visit Pages.

    But you can use get_query_var function. You can get latest database query parameters include post_type, for more information you can look Codex Page. Basically change your code like this;

    add_action( 'admin_notices', 'test');
    function test(){
    $post_type_page = get_query_var('post_type');
    echo $post_type_page;
    }

    Or if you tell us why you want this maybe we can help you with more efficent way :relaxed:

    Cheers!

    Oguz