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 );