最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - WP_enqueue_script inside shortcode?

programmeradmin0浏览0评论

I've got shortcode that needs to include JS library only once and only there where it's used.

function shortcode_function($atts, $content = null) {
    $class = shortcode_atts( array('something' => '0'), $atts );

    return "<script src=\"\"></script> 
            And here goes HTML code for the map.";
}
add_shortcode("sh", "shortcode_function");

The problem is that above example is going to include library several times if maps shortcode is used several times. How can I prevent that? Or more precisely: how can I do it "the correct way"? Can I use wp_enqueue_script() in that place?

Just one requirement: I really need this to include that library only-when-shortcode-is-used.

I've got shortcode that needs to include JS library only once and only there where it's used.

function shortcode_function($atts, $content = null) {
    $class = shortcode_atts( array('something' => '0'), $atts );

    return "<script src=\"http://maps.googleapis/maps/api/js?sensor=false\"></script> 
            And here goes HTML code for the map.";
}
add_shortcode("sh", "shortcode_function");

The problem is that above example is going to include library several times if maps shortcode is used several times. How can I prevent that? Or more precisely: how can I do it "the correct way"? Can I use wp_enqueue_script() in that place?

Just one requirement: I really need this to include that library only-when-shortcode-is-used.

Share Improve this question asked Nov 14, 2012 at 18:00 AtadjAtadj 2,1828 gold badges29 silver badges40 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 4

Yes, you should use wp_enqueue_script(). The script will be loaded in the footer (action: wp_footer()). Just once.

To inspect the order of available hooks, functions etc. per request try my plugin T5 WP Load Order.

We can indeed conditionally load CSS and JS files via shortcode conditionally, when the shortcode is present and without using any overly elaborate functions:

Refer to comment #348349 here: Enqueue Scripts / Styles when shortcode is present

发布评论

评论列表(0)

  1. 暂无评论