首页 > 解决方案 > 如何将我的 JavaScript 文件与 WordPress 中的 enqueue 正确链接

问题描述

我已经确定它wp_head()在头部和wp_footer()身体末端之前。

我的样式表加载正常,但我无法scripts.js加载简单的文件。我尝试了不同的参数等。

编辑:包括:我尝试将它添加到适用于 style.css 的标题中,关闭所有插件,允许使用不同的布尔值,允许使用 null。不同的名称,调用 get_stylesheet_directory 而不是 get_template_directory。

这是我的functions.php

<?php

function load_stylesheets() 
{

    wp_register_style('bootstrap', get_template_directory_uri(). '/css/bootstrap.min.css', array(), false, 'all');
    wp_enqueue_style('bootstrap');

    wp_register_style('style', get_template_directory_uri(). '/style.css', array(), false, 'all');
    wp_enqueue_style('style');
}
add_action('wp_enqueue_scripts', 'load_stylesheets');


function loadJs()
{

    wp_register_script('customjs', get_template_directory_uri(). '/js/scripts.js', '', 1, true);
    wp_enqueue_script('customjs');
}
add_action('wp_enqueue_scripts', 'loadJs');

?>

编辑2:

最奇怪的事情。使用上面列出的代码,我有点放弃并继续在另一个领域工作。突然,大约十五分钟后,js文件被链接了。

在涉及 js 的地方,我所做的所有不同之处是对引导文件进行了解决,并使用 wp_footer() 下方的 CDN 链接将它们链接起来,这工作正常,让我至少可以在那时继续工作。

我不认为这是相关的,但这一切都发生了变化。js文件链接后,我用同样的方法链接bootstrap。同样,它也没有立即链接。我没有更改代码,几分钟后 - 链接。太奇怪了。

标签: wordpresswordpress-themingcustom-wordpress-pages

解决方案


请您尝试使用以下代码:


function load_stylesheets() 
{

    wp_register_style('bootstrap', get_template_directory_uri(). '/css/bootstrap.min.css', array(), false, 'all');
    wp_enqueue_style('bootstrap');

    wp_register_style('style', get_template_directory_uri(). '/style.css', array(), false, 'all');
    wp_enqueue_style('style');
}
add_action('wp_enqueue_scripts', 'load_stylesheets');


function loadJs()
{
    wp_enqueue_script( 'customjs', get_template_directory_uri() . '/js/scripts.js', array(), '1.0.0', true );
}
add_action('wp_enqueue_scripts', 'loadJs');

?>

推荐阅读