[wp-hackers] Best way to detect post type in admin

Mohammad Jangda batmoo at gmail.com
Thu Jul 15 14:01:21 UTC 2010


>
> Nice thks. But $current_screen object is not available at init
> and admin_init time


I ran into the same issue and found that it's better to do the check in
later hooks, since only $_REQUEST['post_type'] works on the init and
admin_init hooks and even then, only on certain pages.

In a plug-in I want to enqueue scripts only on a specific post type new/edit
> form page. What is the best way to achieve it ?


Here's a function I use (in case the formatting gets warped find it here:
http://gist.github.com/476964). It didn't originally have $current_screen,
so thanks for the tip Nacin!

/**
 * Gets the current global post type if one is set
 */
function get_current_post_type() {
global $post, $typenow, $current_screen;
 if( $post && $post->post_type )
$post_type = $post->post_type;
 elseif( $typenow )
$post_type = $typenow;
elseif( $current_screen && $current_screen->post_type )
 $post_type = $current_screen->post_type;
elseif( $_REQUEST['post_type'] )
 $post_type = sanitize_key( $_REQUEST['post_type'] );
else
$post_type = '';
 return $post_type;
}

Note: if you're going to use the function, prefix the name to avoid
conflicts.

--
Mohammad Jangda
www.digitalize.ca | @mjangda


More information about the wp-hackers mailing list