我应该如何开始注册不是文件的JavaScript?

时间:2016-01-03 作者:Tom

对于我正在创建的插件,它会生成自定义JavaScript,这些JavaScript应该在页面的页脚中执行。由于它是自定义JavaScript,我不能简单地将其放入文件并注册&;将文件排队。我应该如何注册自定义JavaScript并将其排队?

注意:这将是一个短代码。JavaScript看起来像这样,

$("#CustomID").aFunction(withCustomData);

同样,我需要在页面的页脚执行它,我不能简单地在短代码中返回它。

编辑1,JavaScript为;“真的”;唯一的它从短代码本身接收参数,并且可能会根据时间而变化。同样,这是一种不断变化的东西,不应该在每次需要加载时都放在文件中。

1 个回复
最合适的回答,由SO网友:Milo 整理而成

你可以钩住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;