function get_current_post_type() { global $post, $typenow, $current_screen, $pagenow; $post_type = NULL; if ($post && $post->post_type) $post_type = $post->post_type; if ($current_screen && $current_screen->post_type) $post_type = $current_screen->post_type; if (empty($post_type)) $post_type = $typenow; if (function_exists('get_current_screen')) { $current_screen = get_current_screen(); $post_type = $current_screen->post_type; } if (isset($_REQUEST['post']) && !empty($_REQUEST['post']) && function_exists('get_post_type')) { $get_post_type = get_post_type((int)$_REQUEST['post']); if ($get_post_type) $post_type = $get_post_type; } if (isset($_REQUEST['post_type']) && !empty($_REQUEST['post_type'])) $post_type = sanitize_key($_REQUEST['post_type']); return $post_type; }
The get_current_post_type() function retrieves the current post type in the WordPress admin panel. It checks various global variables and request parameters to determine the post type.
Here’s how the function works:
- It first checks if the global $post object exists and has a valid post type. If so, it assigns the post type to the $post_type variable.
- It then checks if the global $current_screen object exists and has a valid post type. If so, it updates the $post_type variable.
- If the $post_type variable is still empty, it checks the global $typenow variable and assigns its value to $post_type.
- It checks if the get_current_screen() function exists. If it does, it retrieves the current screen object and updates the $post_type variable with its post type.
- It checks if the $_REQUEST[‘post’] parameter is set and not empty. If so, it uses the get_post_type() function to retrieve the post type based on the post ID provided in the request. If a valid post type is obtained, it updates the $post_type variable.
- 6. Finally, it checks if the $_REQUEST[‘post_type’] parameter is set and not empty. If so, it sanitizes the value and assigns it to $post_type.
The function then returns the determined post type. This function helps in retrieving the current post type dynamically in the WordPress admin panel.
How use:
if(get_current_post_type() == 'sls_item') { //code here }