首先,我要求大家在点击否定箭头之前完整地阅读问题,我真的遇到了一个非常复杂的问题,并且在网上没有找到任何类似的答案。
我想做的:
我正在创建一个wordpress插件安装后,你只需要添加一个短代码和传递一些参数与短代码,然后它会显示一个滑块在你的文章基于你的参数数据。
现在它是一个滑块,它主要是基于jQuery来做一些花哨的东西。现在通过jquery的短代码参数,我采取的帮助wp_localize_script()
,这样我就可以访问jquery脚本中的短代码参数。
问题:
当我将短代码属性值传递给本地化脚本时,我必须在add_shortcode()
块内调用wp_register_script()
, wp_localize_script()
, wp_enqueue_script()
。
因为如果我在add_shortcode()
之外创建另一个函数来排队我的脚本wp wp_enqueue_scripts
动作,那么它会在执行短代码之前先被触发。所以wp_localize_script()
永远不能将短代码属性传递给jquery脚本。
add_shortcode('some_shortcode', function( $atts ) {
//extracting the shortcode attributes
$shortcode_data = shortcode_atts( array(
'arg1' => '',
'arg2' => ''
..... so on....
), $atts );
extract($shortcode_data);
// doing my programming with the shortcode
// in the end echoing some html
/*--------------------------------------*/
// Now coming the script adding part
$dir = plugin_dir_url( __FILE__ );
/* CSS */
wp_enqueue_style( 'some_style', $dir . 'assets/css/some_style.css', null, null );
/* JS */
wp_register_script ('some_script', $dir . 'assets/js/some_script.js');
wp_localize_script( 'some_script', 'someData', $shortcode_data );
wp_enqueue_script( 'some_script', true );
wp_enqueue_script( 'some_other_script', $dir . 'assets/js/some_other_script.js');
});
现在我的插件工作得很好,没有任何问题,但是现在出现了大问题。如果我在一个帖子或页面中包含这个短代码超过一次,它将在每次执行短代码时推送相同的css和js文件。
所以,最后,没有一个短代码会正常工作,因为整个系统都混淆了哪些数据传递给哪个js脚本。
如果你们中有人能帮我解决这个奇怪的问题,那就太有帮助了。我真的不知道如何解决这个奇怪的问题。您可以创建一个不同的函数来检查帖子中是否存在短代码,并为您的滑块排队所需的javascript和css。
。
// Shortcode handler
add_shortcode('some_shortcode', function( $atts ) {
$a = shortcode_atts( array(
'arg1' => '',
'arg2' => ''
), $atts );
/** I would avoid using script localization unless you need script dependancy based on generated js from
* atts data. you can just return the js script directly on your content.
*
*/
$script = '<script>(function {';
$script .= "var arg1 = {$a['arg1']},";
$script .= " arg2 = {$a['arg2']}";
$script .= '})(jQuery);</scipt>';
return script;
});
// Script Dependancy Handling
add_action( 'wp_enqueue_scripts', 'script_style_handler');
function script_style_handler() {
global $post;
//check shortcode existence in post content and enque script/style if found
if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'some_shortcode') && !is_admin() ) {
wp_enqueue_style( 'some_style', $dir . 'assets/css/some_style.css', null, null );
wp_enqueue_script( 'some_other_script', $dir . 'assets/js/some_other_script.js');
}
}