WP-Mix

A fresh mix of code snippets and tutorials

Get Current Post Type in the WordPress Admin Area

In WordPress, you can create posts, pages, or any custom post type. Within your theme template, you can get the current post type using the core WP function, get_post_type(). But that doesn’t work in the Admin Area. For example, my Disable Gutenberg plugin provides conditional functionality to the “Add New” and “Edit” screens based on post type. So how to get the post type in the Admin Area? Here’s one way to do it..

function shapeSpace_get_current_post_type() {
	
	global $post, $typenow, $current_screen;
	
	if ($post && $post->post_type) return $post->post_type;
	
	elseif($typenow) return $typenow;
	
	elseif($current_screen && $current_screen->post_type) return $current_screen->post_type;
	
	elseif(isset($_REQUEST['post_type'])) return sanitize_key($_REQUEST['post_type']);
	
	return null;
	
}

Nothing needs to be edited, just plug and play. Here is an example of how to use in your plugin or theme functions:

if ($post_type = shapeSpace_get_current_post_type()) {
	
	// do stuff with $post_type
}

Source

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress