你的问题是wp_localize_script
将javascript对象打印到html标记,类似于:
var slider = {"id":"a_unique_id_here"};
如果您多次调用它,例如在同一页中使用更多的短代码,那么html标记中的printend是什么
var slider = {"id":"a_unique_id_here"};
var slider = {"id":"another_unique_id_here"};
var slider = {"id":"third_unique_id_here"};
因此,您正在一次又一次地覆盖同一个变量。
您需要这样的东西,您应该将输出转换为如下形式:
var slider_ddAsfe2ser = {"id":"a_unique_id_here"};
var slider_fsdgffereR = {"id":"another_unique_id_here"};
var slider_d4frfAd1ej = {"id":"third_unique_id_here"};
即,必须为每个shorcode创建一个唯一的命名变量作为设置对象。
怎样类似于:
add_shortcode(\'flexslider\', function($atts) {
global $post;
$ids = explode(\',\', $atts[ids]);
$uniqid = uniqid();
wp_enqueue_script( \'shortcode_flexslider\');
$token = wp_generate_password(32, false, false);
wp_localize_script( \'shortcode_flexslider\', \'slider_\' . $token, array(\'id\' => $uniqid));
foreach( $ids as $id ) {
// ... your code here ...
}
$structure = \'<div id="slider\' . $uniqid. \'" class="flexslider"\';
$structure .= \' data-token="\' . $token . \'">\'; // the token as data attribute
$structure .= \'<ul class="slides">\' . $slider . \'</ul></div>\';
$structure .= \'<div id="carousel\' . $uniqid . \'" class="flexslider">\';
$structure .= \'<ul class="slides">\' . $carousel . \'</ul></div>\'
});
之后在你的
js:
// cicle all the divs with \'flexslider\' class and id that starts with \'slider\'
$(\'div.flexslider[id^="slider"]\').each( function() {
var $div = $(this); // the sdiv jquery object
var token = $div.data(\'token\');
// use the bracket syntax to retrieve the unique named object
// in the global (window) scope
var settingObj = window[\'slider_\' + token];
$div.flexslider({
//
sync: \'#carousel\' + settingObj.id
//
});
$carousel = $( \'#carousel\' + settingObj.id); // the carousel div jquery object
$carousel.flexslider({
//
asNavFor: \'#slider\' + settingObj.id
//
});
}); // end each cycle