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?
In your example, there is currently no difference. You get the same object, if there is one. Try it:
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.The
get_current_screen
function actually uses the global $current_screen variable, but what the difference is, is that the functionget_current_screen
performs a check to see if the global variable $current_screen is set and then either returnnull
(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.