How to replace WP string “function.php”

Posted By: | Time: 2019-Jul-27 | Category: Tech | Comment: (0);

How to Improve WordPress Website Loading Speed?

"Render blocking resources" is one of the main reason of low/poor "Website Loading Speed". But what is the render blocking resources?

Render Blocking Resources:

1. By default, CSS is treated as render blocking resources.

To solve this issue you can use rel = "import" attribut with CSS link tag. See the style_loader_tag below as example.

2. Some java-scripts which you call in wp_header is treated as render blocking resources.

To solve this issue you can shift all script in wp_footer manually or use "defer" attribut with script tag which is less important and you have called in header. See the script_loader_tag below as example.

style_loader_tag:

First enqueue your stylesheet, see the WP documentation: here

wp_enqueue_style( ‘bootstrap’, ‘https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css’, array(), null );

style_loader_tag is a WordPress function. See the WP documentation here

apply_filters( ‘style_loader_tag’, $html, $handle, $href, $media )

Here the $handle is 'bootstrap'

Simple string replacement

see the example below:

function add_style_attributes( $html, $handle ) {
if ( ‘bootstrap’ === $handle ) {
return str_replace( “type=’text/css’”, “integrity=’sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T’ crossorigin=’anonymous’ type=’text/css’”, $html );
}
if ( ‘another-style’ === $handle ) {
return str_replace( “type=’text/css’”, “integrity=’xyz’ crossorigin=’anonymous’ type=’text/css’”, $html );
}
return $html;
}
add_filter( ‘style_loader_tag’, ‘add_style_attributes’, 10, 2 );

Add same attribute in all style sheets

function add_attributes_to_all_styles( $html, $handle) {
return str_replace( “rel=’stylesheet’”, “rel=’stylesheet import’”, $html);
return $html;
}
add_filter( ‘style_loader_tag’, ‘add_attributes_to_all_styles’, 10, 2 );

script_loader_tag:

First enqueue your script like style. .Then apply script_loader_tag, see the WP documentation: here

apply_filters( ‘script_loader_tag’, string $tag, string $handle, string $src )

See the below example:

function add_defer_jquery( $tag, $handle ) {
if ( ‘script’ === $handle ) {
return str_replace( “src”, “defer src”, $tag );
}
return $tag;
}
add_filter( ‘script_loader_tag’, ‘add_defer_jquery’, 10, 2 );

Leave a Reply

Your email address will not be published. Required fields are marked *