Using WordPress ‘print_scripts_array’ PHP filter

The ‘print_scripts_array’ filter in WordPress allows you to modify the list of script dependencies that are left to be printed on a page.

Usage

To use the print_scripts_array filter, you need to add a custom function to your WordPress theme or plugin and hook it to the filter using the add_filter() function.

add_filter( 'print_scripts_array', 'your_custom_function_name' );

function your_custom_function_name( $to_do ) {
    // Your custom code here
    return $to_do;
}

Parameters

  • $to_do (string[]) – An array of script dependency handles.

Examples

Remove a specific script

add_filter( 'print_scripts_array', 'remove_specific_script' );

function remove_specific_script( $to_do ) {
    // Remove 'jquery' from the array
    $to_do = array_diff( $to_do, array( 'jquery' ) );
    return $to_do;
}

This code snippet removes the ‘jquery’ script from the list of dependencies to be printed.

Add a custom script before another script

add_filter( 'print_scripts_array', 'add_custom_script_before' );

function add_custom_script_before( $to_do ) {
    // Add custom script before 'jquery'
    array_splice( $to_do, array_search( 'jquery', $to_do ), 0, 'custom-script' );
    return $to_do;
}

This code snippet inserts a custom script called ‘custom-script’ right before the ‘jquery’ script in the list of dependencies to be printed.

Reorder scripts

add_filter( 'print_scripts_array', 'reorder_scripts' );

function reorder_scripts( $to_do ) {
    // Move 'custom-script' to the end of the array
    $to_do = array_diff( $to_do, array( 'custom-script' ) );
    $to_do[] = 'custom-script';
    return $to_do;
}

This code snippet moves the ‘custom-script’ to the end of the list of dependencies to be printed.

Remove all scripts except a specific one

add_filter( 'print_scripts_array', 'keep_specific_script_only' );

function keep_specific_script_only( $to_do ) {
    // Keep only 'jquery' in the array
    $to_do = array_intersect( $to_do, array( 'jquery' ) );
    return $to_do;
}

This code snippet removes all scripts from the list of dependencies to be printed, except for the ‘jquery’ script.

Exclude scripts on specific pages

add_filter( 'print_scripts_array', 'exclude_scripts_on_specific_pages' );

function exclude_scripts_on_specific_pages( $to_do ) {
    // Exclude 'custom-script' on the 'about' page
    if ( is_page( 'about' ) ) {
        $to_do = array_diff( $to_do, array( 'custom-script' ) );
    }
    return $to_do;
}

This code snippet excludes the ‘custom-script’ from the list of dependencies to be printed only on the ‘about’ page.