【问题标题】:Plugin with shortcode, missing .js and .css files when used in widget areas在小部件区域使用时带有短代码、缺少 .js 和 .css 文件的插件
【发布时间】:2018-01-29 08:55:37
【问题描述】:

我正在开发一个 WordPress 插件,如果我在页面或文章中插入短代码,它可以完美运行,但如果我在小部件区域中插入短代码,则不会加载 .js 和 .css 文件。

//CUSTOM JS FUNCTIONS
add_action( 'wp_enqueue_scripts', 'my_functions' );
function my_functions() {
    wp_register_script( 'my-script-1', plugin_dir_url( __FILE__ ) . 'js/functions.js', array( 'jquery' ), '1.0', true );
} 

//CUSTOM CSS
add_action( 'wp_enqueue_scripts', 'my_css' );
function my_css() {
    wp_register_style('my-css', plugin_dir_url( __FILE__ ) . 'css/style.css' );
}

//INCLUDE JS IF SHORTCODE EXIST
add_action( 'wp_print_styles', 'form_my_include' );
function form_my_include() {

    global $post;

    if (strstr($post->post_content, 'my_form_shortcode')) {
        wp_enqueue_script('my-script-1');
        wp_enqueue_style('my-css');
    }
}

//SHORTCODE
function my_shortcode_add(){
    ob_start();
    include("include/my_function.php");
    return ob_get_clean();
}
add_shortcode('my_shortcode', 'my_shortcode_add');

// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');

【问题讨论】:

    标签: wordpress plugins widget shortcode


    【解决方案1】:

    您需要将脚本和样式表直接放入短代码中。您还可以在同一个 wp_enqueue_scripts() 挂钩中同时加载脚本和样式表。

    //CUSTOM JS FUNCTIONS
    add_action( 'wp_enqueue_scripts', 'my_scripts_and_stylesheets' );
    function my_scripts_and_stylesheets() {
        wp_register_script( 'my-script-1', plugin_dir_url( __FILE__ ) . 'js/functions.js', array( 'jquery' ), '1.0', true );
        wp_register_style('my-css', plugin_dir_url( __FILE__ ) . 'css/style.css' );
    } 
    
    //SHORTCODE
    function my_shortcode_add(){
        wp_enqueue_script('my-script-1'); //loaded here
        wp_enqueue_style('my-css'); //loaded here
        ob_start();
        include("include/my_function.php");
        return ob_get_clean();
    }
    add_shortcode('my_shortcode', 'my_shortcode_add');
    
    // Enable shortcodes in text widgets
    add_filter('widget_text', 'do_shortcode');
    

    您当前的代码抓取帖子内的内容,并检查其中的短代码。根据调用短代码的位置,它可能实际上并不存在于帖子内容中,尽管它存在于页面上。

    通过将wp_enqueue_script()wp_enqueue_style() 添加到您的简码函数中,只要您的简码出现在页面上,无论它在页面的哪个位置,它都会将您排入队列。

    【讨论】:

      【解决方案2】:

      将此代码添加到您的插件中。

      // Enable shortcodes in text widgets
      add_filter('widget_text','do_shortcode');
      

      此代码只是添加了一个新过滤器,允许短代码在小部件内运行。

      【讨论】:

      • 添加过滤器,但不起作用,js和css无法加载。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 2016-02-29
      • 1970-01-01
      • 2017-02-25
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多