Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get the current post_type context in the WordPress admin.
<?php
/**
* gets the current post type in the WordPress Admin
*/
function get_current_post_type() {
global $post, $typenow, $current_screen;
//we have a post so we can just get the post type from that
if ( $post && $post->post_type ) {
return $post->post_type;
}
//check the global $typenow - set in admin.php
elseif ( $typenow ) {
return $typenow;
}
//check the global $current_screen object - set in sceen.php
elseif ( $current_screen && $current_screen->post_type ) {
return $current_screen->post_type;
}
//check the post_type querystring
elseif ( isset( $_REQUEST['post_type'] ) ) {
return sanitize_key( $_REQUEST['post_type'] );
}
//lastly check if post ID is in query string
elseif ( isset( $_REQUEST['post'] ) ) {
return get_post_type( $_REQUEST['post'] );
}
//we do not know the post type!
return null;
}
@gmsdesignworks

This comment has been minimized.

Copy link

@gmsdesignworks gmsdesignworks commented Jul 20, 2016

works perfectly. nice job. :)

@socialmedialabs

This comment has been minimized.

Copy link

@socialmedialabs socialmedialabs commented Oct 6, 2016

Exactly what I was looking for. Thanks for this!

@b0tm1nd

This comment has been minimized.

Copy link

@b0tm1nd b0tm1nd commented Jan 8, 2017

Me too.

@Codevz

This comment has been minimized.

Copy link

@Codevz Codevz commented Jun 9, 2017

Thanks

@danyj

This comment has been minimized.

Copy link

@danyj danyj commented Dec 8, 2017

nice one but no need for $_REQUEST, is more expensive
https://stackoverflow.com/a/1924969/594423

$_GET does the job nicely and we just need variables from the querystring

@jamiechong

This comment has been minimized.

Copy link

@jamiechong jamiechong commented Feb 27, 2018

This doesn't work for me when I'm viewing the Posts archives (/wp-admin/edit.php). Expect post

@jamiechong

This comment has been minimized.

Copy link

@jamiechong jamiechong commented Feb 27, 2018

Work around. Modify to: global $post, $typenow, $current_screen, $pagenow; Then add this just before return null.

else if ( $pagenow == 'edit.php' ) {
    $type = 'post';
}
@carasmo

This comment has been minimized.

Copy link

@carasmo carasmo commented Aug 10, 2018

Thank you!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment