我正在尝试将 javascript 文件链接到我的子主题。我已经查看了 WordPress Codex 和大量示例,但它仍然无法正常工作。我正在本地主机上工作,所以根据我所读到的内容,我想使用 get_stylesheet_directory()。我已经重复了它,它指向了正确的路径。下面是我的代码,放置在我的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 );
}
我的 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 );
最佳答案
队列中的 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 );
}
关于javascript - 将 javascript 文件链接到 WordPress 子主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088842/