你可以钩住wp_footer 输出任意JavaScript的操作。这与WordPress用于输出页脚排队脚本的操作相同。
下面是一个将短代码、数据和脚本输出封装在类中的示例:
<?php
/*
Plugin Name: WPD_Example
*/
class WPD_Example_Plugin {
public $data = array();
function __construct() {
add_shortcode( \'wpd_example\', array( $this, \'shortcode_func\' ) );
add_action( \'wp_footer\', array( $this, \'footer_scripts\' ), 9999 );
}
function shortcode_func( $atts ) {
$atts = shortcode_atts( array(
\'title\' => \'title\'
), $atts, \'wpd_example\' );
$id = uniqid();
$this->data[$id] = $atts[\'title\'];
wp_enqueue_script( \'jquery\' );
return \'<div data-id="\' . $id . \'">\' . $atts[\'title\'] . \'</div>\';
}
function footer_scripts() {
if( !empty( $this->data ) ){
?>
<script type="text/javascript">
if ( undefined !== window.jQuery ) {
jQuery(document).ready(function($) {
var myData = <?php echo wp_json_encode( $this->data ); ?>;
$.each( myData, function( id, title ) {
console.log( id + \' : \' + title );
});
});
}
</script>
<?php
}
}
}
$wpd_plugin = new WPD_Example_Plugin;
<小时>
EDIT
下面是另一个与上面类似的示例,但将脚本排队并通过
wp_localize_script 而不是直接将js打印到页面。您可以从
wpdScriptData js对象。阅读此答案下面的注释,了解此方法更安全的原因。
<?php
/*
Plugin Name: WPD_Example
*/
class WPD_Example_Plugin {
public $data = array();
function __construct() {
add_shortcode( \'wpd_example\', array( $this, \'shortcode_func\' ) );
add_action( \'wp_footer\', array( $this, \'footer_scripts\' ), 0 );
}
function shortcode_func( $atts ) {
$atts = shortcode_atts( array(
\'title\' => \'title\'
), $atts, \'wpd_example\' );
$id = uniqid();
$this->data[$id] = $atts[\'title\'];
wp_enqueue_script( \'jquery\' );
wp_enqueue_script( \'wpd-script\', plugins_url( \'/js/script.js\', __FILE__ ), array( \'jquery\' ), null, true );
return \'<div data-id="\' . $id . \'">\' . $atts[\'title\'] . \'</div>\';
}
function footer_scripts() {
if( !empty( $this->data ) ){
wp_localize_script(
\'wpd-script\',
\'wpdScriptData\',
$this->data
);
}
}
}
$wpd_plugin = new WPD_Example_Plugin;