4

I have this code

function this_is_my_shortcode(){
    wp_register_script('per-pas-belanja-online', plugins_url('js/per-pas-belanja-online.js', __FILE__), array('jquery'), '1.0.0');
    wp_enqueue_script('per-pas-belanja-online');
    return '<div id="poppedout">Blah</div>';
}
add_shortcode('bubba', 'this_is_my_shortcode');

The div is appear on the page, but the script is not. What mistake i have done ?

  • 8
    as of WordPress 3.3 your code should work just fine – Bainternet Feb 16 '12 at 1:39
2

Straight from the Codex

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side. Calling it outside of an action can lead to troubles.

  • 1
    To clarify: in order to take effect, a script must be enqueued before WordPress actually prints those enqueued scripts (which takes place within the wp_head hook - which itself includes a long list of actions that take place, including printing of enqueued scripts and styles). Once WordPress is outputting Post content, you are well past that point. – Chip Bennett Jun 8 '11 at 12:56
  • 1
    Thanks for the explanation. That makes everything clear. But, I want to enqueue script only when user use that shortcode. Is there a way to achieve that ? – Permana Jun 9 '11 at 0:56
2

As @Bainternet pointed out as of 3.3 it should work just fine for js (described by scribu here). For those also wanting to conditionally load css, it's still difficult but these two articles by beerpla and one by iandunn should pave the way.

0

You should enqueue scripts like this:

function this_is_my_shortcode(){
    add_action('wp_enqueue_scripts', function() {
        wp_register_script('per-pas-belanja-online', plugins_url('js/per-pas-belanja-online.js', __FILE__), array('jquery'), '1.0.0');
        wp_enqueue_script('per-pas-belanja-online');
    });
    return '<div id="poppedout">Blah</div>';
}
add_shortcode('bubba', 'this_is_my_shortcode');

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.