【问题标题】:Wordpress plugin load js and css on demandWordpress 插件按需加载 js 和 css
【发布时间】:2015-04-10 02:00:11
【问题描述】:

我用简码创建了插件。仅当我使用插件(我的帖子中的短代码)时,我才想加载插件的 js 和 css。我发现了几个例子,我创造了这样的东西。是正确的方法吗?一切正常,但我在页面源代码中看不到这些脚本(我检查了 Firefox 和 chrome)

   public function __construct(){       
        add_shortcode( $this->tag, array($this, 'run_yoolek' ) );
        add_action( 'wp_enqueue_scripts',  array( $this, 'register_my_script' ) );  
    }

    public function run_yoolek(){

        wp_enqueue_style('yoolek-googlemap-simple-css');
        wp_enqueue_script('google-maps');
        wp_enqueue_script( 'yoolek-googlemap-simple-js' );

        ob_start();
        ...
        return ob_get_clean();
    } 

    public function register_my_script() {
        wp_register_style( 'yoolek-googlemap-simple-css',plugins_url( '/style.css' , __FILE__ ) );
        wp_register_script( 'google-maps', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAM10sMY' );
        wp_register_script( 'yoolek-googlemap-simple-js', plugins_url( '/script.js' , __FILE__ ) );

    }   

【问题讨论】:

    标签: javascript css wordpress plugins


    【解决方案1】:

    wp_enqueue_style() 和 wp_enqueue_script() 在这个地方不起作用,你应该在另一个函数中使用它们,例如 wp_enqueue_scripts 钩子的 my_scripts_method()。

      add_action( 'wp_enqueue_scripts', array($this, 'my_scripts_method') );
    

    【讨论】:

    • 您好,谢谢您的回答。 “在这个地方不起作用”是什么意思-我对其进行了测试并且它有效,但我不知道这是否是正确的方法。我正在寻找最佳解决方案。你想让我把员工从函数 run_yoolek 转移到 my_script_method?(入队)。你觉得其他的还好吗?
    • 是的,我认为,在 wp_register_script() 调用之后,您应该将 wp_enqueue_script 调用移至您的 register_my_script() 函数
    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 2019-06-20
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 2019-04-15
    相关资源
    最近更新 更多