简体   繁体   English

将javascript文件链接到wordpress子主题

[英]linking javascript file to wordpress child theme

I'm trying to link a javascript file to my child theme. 我正在尝试将javascript文件链接到我的子主题。 I've looked at the WordPress Codex and numerous examples, but it still is not working. 我看过WordPress Codex和众多示例,但仍然无法正常工作。 I'm working on localhost, so from what I have read, i want to use the get_stylesheet_directory(). 我正在localhost上工作,所以从我读到的内容来看,我想使用get_stylesheet_directory()。 I've echoed it out and it is pointing to the correct path. 我已经回声了,它指向正确的路径。 Below is my code that is placed in my functions.php child theme: 以下是放在我的functions.php子主题中的代码:

add_action( 'wp_enqueue_scripts', 'theme_js' );
function theme_js() {
wp_enqueue_script( 'theme_js', get_stylesheet_directory() . '/js/theme.js',    array('jquery'), '', true );
}

My javascript file looks like this: 我的JavaScript文件如下所示:

/**
 * Custom Theme Styles
 */
( function( $ ) {

$('.main-navigation li a').click(function() {
    var link = $(this).attr('href');
    $('html, body').animate({
    scrollTop: $(link).offset().top
    }, 1500);
});
 })( jQuery );

You have to register the script first, then enqueue it. 您必须先注册脚本,然后使其入队。 Here is the codex: http://codex.wordpress.org/Function_Reference/wp_register_script 这是编解码器: http : //codex.wordpress.org/Function_Reference/wp_register_script

The src string in the enqueue needs to be a URL, not a path, so you need to use get_stylesheet_directory_uri() instead of get_stylesheet_directory() : 入队中的src字符串必须是URL,而不是路径,因此您需要使用get_stylesheet_directory_uri()而不是get_stylesheet_directory()

add_action( 'wp_enqueue_scripts', 'theme_js' );
function theme_js() {
    wp_enqueue_script( 'theme_js', get_stylesheet_directory_uri() . '/js/theme.js',    array('jquery'), '', true );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM