Using WordPress ‘print_head_scripts()’ PHP function

The print_head_scripts() WordPress PHP function prints the script queue in the HTML head on admin pages.

Usage

print_head_scripts();

Parameters

  • None

More information

See WordPress Developer Resources: print_head_scripts()

Examples

Enqueue a custom script and use print_head_scripts()

This example demonstrates how to enqueue a custom script and use print_head_scripts() to print it in the head section of the admin pages.

function my_custom_script() {
    wp_enqueue_script('my-script', get_template_directory_uri() . '/js/my-script.js', array('jquery'), '1.0', true);
    print_head_scripts();
}
add_action('admin_enqueue_scripts', 'my_custom_script');

Enqueue a script with dependencies and use print_head_scripts()

This example demonstrates how to enqueue a script with dependencies and use print_head_scripts() to print it in the head section of the admin pages.

function enqueue_custom_script_with_dependencies() {
    wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery', 'underscore'), '1.0', true);
    print_head_scripts();
}
add_action('admin_enqueue_scripts', 'enqueue_custom_script_with_dependencies');

Remove a script from the queue and use print_head_scripts()

This example demonstrates how to remove a script from the queue and use print_head_scripts() to print the remaining scripts in the head section of the admin pages.

function remove_script_and_print_head_scripts() {
    wp_dequeue_script('unwanted-script');
    print_head_scripts();
}
add_action('admin_enqueue_scripts', 'remove_script_and_print_head_scripts');

Modify the script queue and use print_head_scripts()

This example demonstrates how to modify the script queue, removing one script and adding another, and use print_head_scripts() to print the updated queue in the head section of the admin pages.

function modify_script_queue_and_print_head_scripts() {
    wp_dequeue_script('unwanted-script');
    wp_enqueue_script('new-script', get_template_directory_uri() . '/js/new-script.js', array('jquery'), '1.0', true);
    print_head_scripts();
}
add_action('admin_enqueue_scripts', 'modify_script_queue_and_print_head_scripts');

Conditionally enqueue a script and use print_head_scripts()

This example demonstrates how to conditionally enqueue a script based on user capabilities and use print_head_scripts() to print the script queue in the head section of the admin pages.

function conditionally_enqueue_script_and_print_head_scripts() {
    if (current_user_can('manage_options')) {
        wp_enqueue_script('admin-script', get_template_directory_uri() . '/js/admin-script.js', array('jquery'), '1.0', true);
    }
    print_head_scripts();
}
add_action('admin_enqueue_scripts', 'conditionally_enqueue_script_and_print_head_scripts');