2

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.

2

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.

  • Thanks! it works. I will mark as answered when I'll be able (it tells me I can only in two more minutes) – Omer Aug 11 '18 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.