Is $hook a global variable in WordPress

// only run on dashboard page
if ( 'index.php' != $hook ) {
    return;
}

There is a plugin on the WordPress.org repository that checks PHP current version. I happened to read its code and came across the above code.

the comment tells everything that only runs on the Dashboard page.

But is $hook a global WP function? I am unable to make a sense of this. Please help me or in case if any suggested readings.

Display-php-version.php →

function dpv_enqueue_script( $hook ) {

    // only run on dashboard page
    if ( 'index.php' != $hook ) {
        return;
    }

    // enqueue script to show PHP version
    wp_enqueue_script( 'dpv_script', plugin_dir_url( __FILE__ ) . 'dpv.js' );

    // pass the PHP version to JavaScript
    wp_localize_script( 'dpv_script', 'dpvObj', array(
        'phpVersion' => phpversion()
    ) );

}

add_action( 'admin_enqueue_scripts', 'dpv_enqueue_script' );

Code on dpv.js →

jQuery(document).ready(function ($) {
    $("#wp-version-message").after("<p>Running PHP version: <b style='color:green;'>" + dpvObj.phpVersion + "</b></p>");
});

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Ok – so, firstly you should know that it is a variable and not a function – in php this is indicated by the dollar symbol before the name: $variable as opposed to function()

Second, you should note that $hook is passed as a parameter to the function block – like so:

function_name( $hook ){

    // this makes the variable $hook available inside the function - not globally.
    echo $hook;

}

So, $hook is actually passed to the function from the “hook” admin_enqueue_scripts which you can read on the codex page describes the value as $hook as:

Parameters

$hook_suffix
(string) The current admin page.

So, the answer is that $hook is not a global variable, nor a function ( essentially all WordPress functions are global, but that is another point ) – it is a local variable passed into the scope of the function hooked to the action.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x