Home > Back-end >  How to add attribute to the script in php
How to add attribute to the script in php

Time:10-09

I have a link to the script in my HTML

  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCrAbBwliakQCs7vDgLGilKQnicEc0-8hA&callback=initMap&v=weekly" defer></script>

I need to add attribute "defer" in my php when using "wp_dequeue_style"

wp_enqueue_script('google-map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCrAbBwliakQCs7vDgLGilKQnicEc0-8hA&callback=initMap&v=weekly', [], $version, true);

is it any options?

CodePudding user response:

Please add this in your functions.php file and check again.

add_action( 'wp_enqueue_scripts', 'qcpd_wp_script_to_scripts', 20, 1);
if (!function_exists('qcpd_wp_script_to_scripts')) {
    function qcpd_wp_script_to_scripts(){

        wp_enqueue_script('google-map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCrAbBwliakQCs7vDgLGilKQnicEc0-8hA&callback=initMap&v=weekly', [], '', true);
    }
}


add_filter( 'script_loader_tag', 'qcpd_wp_script_defer_load_js', 100, 3 );
if (!function_exists('qcpd_wp_script_defer_load_js')) {
function qcpd_wp_script_defer_load_js( $tag, $handle, $src ) {
    //$defer_load_js = true;

        $handles = array(  
                        'google-map'
                    );
     
        if ( ! wp_is_mobile() && in_array( $handle, $handles ) ) {

            return str_replace(' src', ' defer src', $tag);
            
        }
    

        return $tag;

    }
}

CodePudding user response:

You can't do it using wp_enqueue_script you will have to use some other script loader hooks and add the defer.

Please check this article it has the explanation and code that will help you.

  • Related