0

I have the following code in functions.php. The first function correctly enqueues the script based on the page name. However, the second function always adds the 'defer' attribute.

function custom_scripts() {
    global $page;
    if ($page->page_name !== 'awkward_page') {
        wp_enqueue_script('jquery');
    }

    // ...
}
add_action( 'wp_enqueue_scripts', 'custom_scripts' );


function defer_scripts( $tag, $handle ) {
    global $page;
    if ($page->page_name !== 'awkward_page') {
        return str_replace( ' src', ' defer src', $tag );
    }
    return $tag;
}
add_filter( 'script_loader_tag', 'defer_scripts', 10, 2 );

What is wrong with this code?

If this is the wrong way to conditionally add the 'defer' html attribute, what is the correct way?

1

The global $page variable is not a WP_Post object. It is just the post ID. So to get the page title, you need to get the WP_Post object first from the post ID.

The reason that defer is always getting added is two-fold. First, $page is an integer, so $page->page_name will evaluate as null and null is not identically equal to 'awkward_page'. It will also throw an error or warning. Also, page_name is not a valid property of a WP_Post object. The correct property is post_name - even on pages.

function defer_scripts( $tag, $handle ) {

    //* Get the post object
    $page = get_post( get_the_ID() );

    //* Defer on some condition
    if( 'awkward_page' !== $page->post_name ) {
      $tag = str_replace( ' src', ' defer src', $tag );
    }
    return $tag;
}
add_filter( 'script_loader_tag', 'defer_scripts', 10, 2 );

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.