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 ?

1
  • 8
    as of WordPress 3.3 your code should work just fine Commented Feb 16, 2012 at 1:39

3 Answers 3

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.

2
  • 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. Commented Jun 8, 2011 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 ? Commented Jun 9, 2011 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 and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.