Use wc_enqueue_js only on specific pages

by Ryszard JÄ™draszyk   Last Updated August 14, 2019 01:08 AM

In my plugin, I'm trying to add inline script using wc_enqueue_js only on the cart page. The rest of the plugin is also executed only on the cart page.

The code below works fine, but I don't like the fact that I need to repeat if (! is_cart() ) return;. This may not look like a big issue, but my other plugin with a similar problem has several lines of conditions based on what the user selected in plugin settings, that are mixed with multiple actions:

// Run plugin.
add_action( 'template_redirect', function() use ( $args ) { ajax_cart_autoupdate( $args ); });
function ajax_cart_autoupdate( $args ) {    
    if (! is_cart() ) return; // Only if it's a cart page.  
    // Do stuff.    
}

// Enqueue js script inline using wc_enqueue_js.
add_action( 'template_redirect', function() use ( $args ) { acau_enqueue_script ( $args ); });
function acau_enqueue_script( $args ) { 
    if (! is_cart() ) return; // Only if it's a cart page.  
    wc_enqueue_js( '    
        <<<my jquery code>>>
    ' );    
}

The following doesn't work - the inline script doesn't appear in the HTML:

// Run plugin.
add_action( 'template_redirect', function() use ( $args ) { ajax_cart_autoupdate( $args ); });
function ajax_cart_autoupdate( $args ) {
    if (! is_cart() ) return; // Only if it's a cart page.
    // Enqueue js script inline using wc_enqueue_js.
    add_action( 'template_redirect', function() use ( $args ) { acau_enqueue_script ( $args ); });
    // Do stuff.    
}

function acau_enqueue_script( $args ) { 
    wc_enqueue_js( '    
        <<<my jquery code>>>
    ' );    
}

The following works, but the inline script appears in the HTML twice (one script directly below the other). If I put echo 'test'; in the first line of function acau_enqueue_script, it appears only one time on page:

// Run plugin.
add_action( 'template_redirect', function() use ( $args ) { ajax_cart_autoupdate( $args ); });
function ajax_cart_autoupdate( $args ) {
    if (! is_cart() ) return; // Only if it's a cart page.
    // Enqueue js script inline using wc_enqueue_js.
    add_action( 'wp_enqueue_script', function() use ( $args ) { acau_enqueue_script ( $args ); });
    // Do stuff.    
}

function acau_enqueue_script( $args ) { 
    wc_enqueue_js( '    
        <<<my jquery code>>>
    ' );    
}

Is there any smart way to make it work without repeating page conditions?



Related Questions


Add city name field to shipping zone - Woocommerce

Updated April 10, 2018 06:08 AM

integrate a payment gateway with woocommerce

Updated November 30, 2017 13:08 PM


woocommerce_order_status_completed Not being called

Updated February 16, 2019 22:08 PM