从Wordpress中的自定义插件加载脚本

时间:2017-08-18 15:56:42

标签: javascript jquery wordpress plugins

我在我的主插件文件中有这个(/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");
});

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

1 个答案:

答案 0 :(得分: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");
});
相关问题