【问题标题】:Loading scripts from custom plugin in Wordpress从 Wordpress 中的自定义插件加载脚本
【发布时间】:2017-08-18 15:56:42
【问题描述】:

我的主插件文件中有这个 (/plugins/oglasi/oglasi.php)

<?php
 /*
 Plugin Name: Oglasi
 Plugin URI: 
 Description: Custom post type "Oglasi".
 Version: 1.0
 Author: Dragi
 Author URI:
 License: GPLv2
 */

function james_adds_to_the_head() {
    wp_register_script( 'add-bx-js', plugin_dir_url( __FILE__ ) . 'js/filter-oglasi.js', array('jquery'),'',true  ); 
}

add_action( 'wp_enqueue_scripts', 'james_adds_to_the_head' );

这里 /plugins/oglasi/js/filter-oglasi.js 我有:

jquery(document).ready(function() {

    console.log("MAIN IS LOADED");
    alert("Dragi");
});

但它不起作用。有人可以帮忙吗?

【问题讨论】:

    标签: javascript jquery wordpress plugins


    【解决方案1】:

    wp_register_script() 注册一个脚本,稍后使用wp_enqueue_script() 函数将其排入队列。使用wp_enqueue_script('add-bx-js') 加载注册脚本。这意味着,如果您想注册您的脚本,但不直接将它们加载到您的页面中,您可以注册一次文件,然后在需要时加载它们。

    使用以下代码:

    function james_adds_to_the_head() {
        wp_register_script( 'add-bx-js', plugin_dir_url( __FILE__ ) . 'js/filter-oglasi.js', array('jquery'),'',true  ); 
        wp_enqueue_script( 'add-bx-js' );
    }
    
    add_action( 'wp_enqueue_scripts', 'james_adds_to_the_head' );
    

    或:

    function james_adds_to_the_head() {
        wp_enqueue_script( 'add-bx-js', plugin_dir_url( __FILE__ ) . 'js/filter-oglasi.js', array('jquery'),'',true  );
    }
    
    add_action( 'wp_enqueue_scripts', 'james_adds_to_the_head' );
    

    更多信息:

    https://wordpress.stackexchange.com/questions/82490/when-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque

    https://developer.wordpress.org/reference/functions/wp_register_script/

    更新

    您的 js 文件中有错误。如下使用jQuery 而不是jquery,然后使用CTRL+F5 强制刷新浏览器缓存。也可以使用wp_register_script()第四个参数——版本参数——强制刷新资源。

    jQuery(document).ready(function() {
    
        console.log("MAIN IS LOADED");
        alert("Dragi");
    });
    

    【讨论】:

    • 抱歉,它仍然无法正常工作。我仍然可以在控制台中看到消息或警报。如果将代码放在主题的 functions.php 文件中,这可以工作,但我想在插件中执行此操作。还有什么想法吗?谢谢。
    • wp_enqueue_script() 适用于主题和插件。检查您的浏览器控制台是否有 404 或 403 错误,并在浏览器页面源中搜索您的文件名。
    • 检查答案更新。代码经过测试并且工作正常。
    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多