Using WordPress ‘convert_to_screen()’ PHP function

The convert_to_screen() WordPress PHP function converts a screen string into a screen object.

Usage

Let’s say we have a screen string 'edit-post' and we want to convert it into a screen object.

$screen = convert_to_screen('edit-post');

After running the above code, $screen will be an object representing the 'edit-post' screen.

Parameters

  • $hook_name (string – Required) – The hook name, also known as the hook suffix, used to determine the screen.

More information

See WordPress Developer Resources: convert_to_screen

This function is part of the core WordPress functionality and is used extensively within the admin area for screen-specific actions and filters.

Examples

Convert ‘edit-post’ to screen object

This example shows how you can convert a string 'edit-post' to a screen object.

// Convert string to screen object
$screen = convert_to_screen('edit-post');

// Display the id of the screen object
echo $screen->id;

In this example, the echo $screen->id; will output 'edit-post', as that is the ID of the screen object created.

Check if current screen is ‘edit-post’

You can use the convert_to_screen() function to check if the current screen is ‘edit-post’.

$current_screen = get_current_screen();
$edit_post_screen = convert_to_screen('edit-post');

if ($current_screen->id == $edit_post_screen->id) {
    echo 'You are on the edit post screen!';
}

If the current screen is ‘edit-post’, you will see ‘You are on the edit post screen!’ message.

Add Help Tab to ‘edit-post’ screen

In this example, we’ll add a help tab to the ‘edit-post’ screen using convert_to_screen().

$screen = convert_to_screen('edit-post');

$screen->add_help_tab(array(
    'id' => 'your_tab_id',
    'title' => 'My Help Tab',
    'content' => '<p>Some helpful content</p>',
));

After running this code, a new help tab titled ‘My Help Tab’ with the content ‘Some helpful content’ will appear on the ‘edit-post’ screen.

Convert ‘themes’ to screen object

This example shows how to convert the ‘themes’ string into a screen object.

$screen = convert_to_screen('themes');
echo $screen->id;

In this case, the echo $screen->id; will output 'themes'.

Add Action to ‘themes’ screen

Here, we add an action specifically for the ‘themes’ screen.

$screen = convert_to_screen('themes');

// Ensure the current screen is 'themes'
if (get_current_screen()->id == $screen->id) {
    add_action('admin_footer', 'my_custom_function');
}

In this example, my_custom_function will be hooked to the ‘admin_footer’ only if the current screen is ‘themes’.