I am trying to create a plugin and I’ve got stuck. I am trying to register and enqueue a script from a shortcode:
This is my shortcode:
add_shortcode( 'gear-guide', 'gg_product_front_end' );
This is the function it calls to:
function gg_product_front_end() {
echo '<p id="test">Test!</p>';
wp_register_script( 'gg_loadProducts_frontEnd', plugins_url( 'js/front_end.js', __FILE__ ), array( 'jquery' ));
wp_enqueue_script( 'gg_loadProducts_frontEnd' );
}
And this is the JavaScript:
function gg_loadProducts_frontEnd() {
console.log( 'Test!' );
}
JavaScript doesn’t work, but I am not getting any error, neither php nor js.
1 Answer
You need to return the Shortcode generated string, not echo
, like this:
function gg_product_front_end() {
wp_register_script( 'gg_loadProducts_frontEnd', plugins_url( 'js/front_end.js', __FILE__ ), array( 'jquery' ));
wp_enqueue_script( 'gg_loadProducts_frontEnd' );
return '<p id="test">Test!</p>';
}
Also, you need to call the JavaScript function, like this:
function gg_loadProducts_frontEnd() {
console.log( 'Test!' );
}
gg_loadProducts_frontEnd();
Otherwise Test!
will not be logged in Browser Console.
Also, check This Post to enqueue Scripts / styles when shortcode is present.