5

I have been looking at get_current_screen();. I have seen there is also a global $current_screen; that I could use.

Here are two examples:

// Using function
function wpse_post_notice() {

    $screen = get_current_screen();

    // Only run in post/page creation and edit screens
    if ( $screen->post_type === 'post' ) {
        return 'This is a post';
    }

}

// Using gloabl
function wpse_post_notice() {

    global $current_screen;

    // Only run in post/page creation and edit screens
    if ( $current_screen->post_type === 'post' ) {
        return 'This is a post';
    }

}

Is one method considered better than the other? If so why?

4

In your example, there is currently no difference. You get the same object, if there is one. Try it:

global $current_screen;
$current_screen->foo = 1;

$screen = get_current_screen();
$screen->foo = 2;

echo '$current_screen->foo: ' . $current_screen->foo; // 2!

The simple reason: objects are not passed as a copy in PHP.

But: global variables are really bad, because everyone can change them any time. One day far, far away, WordPress might deprecate this global variable. If you are using the function wrapper to get the object, you should be fine. Otherwise, your code might raise notices.

And always check if you get indeed an object. $current_screen->post_type might not exist.

0

The get_current_screen function actually uses the global $current_screen variable, but what the difference is, is that the function get_current_screen performs a check to see if the global variable $current_screen is set and then either return null (if the variable isn't set) or $current_screen.

I regards to this I would suggest you to use the get_current_screen function so you include this extra isset check.

See it in the WordPress sourcecode (wp-admin/includes/screen.php) line 174.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.