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?
add_action
from the default (10) to 20, causing the parent and childadd_action
to have a different priority solved the problem and now everything works perfectly:add_action( 'template_redirect', function() use ( $args ) { acau_enqueue_script ( $args ); }, 20);
I would be grateful for an answer why this is the case. – Ryszard Jędraszyk Aug 14 '19 at 1:43