如何在functions.php(wordpress)中加载引导程序脚本和样式

How to load bootstrap script and style in functions.php (wordpress)?

本文关键字:加载 引导程序 脚本 样式 wordpress functions php      更新时间:2023-09-26

我将引导程序主题转换为wordpress。现在,我在加载引导程序脚本和样式时遇到了一个问题。这是我在functions.php 中的代码

   function wpbootstrap_scripts_with_jquery()
    {
        // Register the script like this for a theme:
        wp_register_script( 'custom-script', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ) );
        wp_enqueue_script( 'samplejs', get_template_directory_uri() . '/js/jquery.min.js', array( '' ) );
            wp_enqueue_script( 'samplejs', get_template_directory_uri() . '/js/clean-blog.min.js', array( '' ) );
        // For either a plugin or a theme, you can then enqueue the script:
        wp_enqueue_script( 'custom-script' );
    }
add_action( 'wp_enqueue_scripts', 'wpbootstrap_scripts_with_jquery' );

我把这个添加到我的头中

<?php wp_enqueue_script("jquery"); ?>

附加问题:wp_register和wp_enqueue之间有什么区别?请帮帮我。我是使用引导程序的初学者。

您所需要做的就是将它们排入队列。此外,我建议取消jquery导入(第二个wp_enqueue)。WordPress默认包含jQuery,并且您已经将其包含在第一个脚本中(因为您已将其列为依赖项)。这里有一个例子,但它将jquery排队两次(本地jquery和引导程序jquery):

function wpbootstrap_scripts_with_jquery()
{
    // Register the script like this for a theme:
    wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/bootstrap.js', array( 'jquery' ) );
    wp_enqueue_script( 'bootstrap-jquery', get_stylesheet_directory_uri() . '/js/jquery.min.js' );
    wp_enqueue_script( 'blog-scripts', get_stylesheet_directory_uri() . '/js/clean-blog.min.js' );
}
add_action( 'wp_enqueue_scripts', 'wpbootstrap_scripts_with_jquery' );

在将脚本排入队列之前,您需要注册这些脚本的唯一原因是其中一个脚本是依赖项。来自文档:

wp_register_script()在WordPress中注册要链接的脚本文件稍后使用wp_enque_script()函数将处理脚本依赖关系。

已使用wp_register_script()预注册的脚本执行不需要使用wp_enque_script()手动排队,如果它们是列为排队的另一个脚本的依赖项。WordPress将自动包括已注册的脚本,然后再包括将已注册脚本的句柄列为依赖性。

您可以使用"wp_enque_style"answers"wp_eenque_script"。

例如:

function reg_scripts() {
    wp_enqueue_style( 'bootstrapstyle', get_template_directory_uri() . '/css/bootstrap.min.css' );
    wp_enqueue_style( 'bootstrapthemestyle', get_template_directory_uri() . '/css/bootstrap-theme.min.css' );
    wp_enqueue_script( 'bootstrap-script', get_template_directory_uri() . '/js/bootstrap.min.js', array(), true );
}
add_action('wp_enqueue_scripts', 'reg_scripts');