Use wc_enqueue_js only on specific pages

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 would need to be repeated:

// 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?

Read more here:: Use wc_enqueue_js only on specific pages

Leave a Reply

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