akselrows akselrows - 5 months ago 11
jQuery Question

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

I converted bootstrap theme to wordpress. Now, I have a problem in loading the bootstrap scripts and style.
This is my code in 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' );


and i add this in my header

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


Additional question:
What is the difference between wp_register and wp_enqueue?
Please help me. Im beginner in using bootstrap.

Answer

All you need to do is enqueue them. Also, I recommend getting rid of your jquery import (the second wp_enqueue). WordPress includes jQuery by default, and you're already including it in the first script (because you have listed it as a dependency). Here's an example, but this enqueues jquery twice (the native jquery, and the bootstrap 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' );

The only reason you'd need to register the scripts before enqueue-ing them, is if one of the scripts is a dependency. From the docs:

wp_register_script() registers a script file in WordPress to be linked to a page later using the wp_enqueue_script() function, which safely handles the script dependencies.

Scripts that have been pre-registered using wp_register_script() do not need to be manually enqueued using wp_enqueue_script() if they are listed as a dependency of another script that is enqueued. WordPress will automatically include the registered script before it includes the enqueued script that lists the registered script's handle as a dependency.