Check for post type in admin panel. WordPress function example

Check for post type in admin panel. WordPress function example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: Wordress 4.0+, PHP 5.6 +
1
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:

  1. 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.
  2. It then checks if the global $current_screen object exists and has a valid post type. If so, it updates the $post_type variable.
  3. If the $post_type variable is still empty, it checks the global $typenow variable and assigns its value to $post_type.
  4. 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.
  5. 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. 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
}
0

More

Comments (1)

Leave a Reply

Your email address will not be published. Required fields are marked *

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation