3

I'm a beginner in WordPress, in WordPress is there a way to load JS/CSS file to a specific page, when page is called, and not to load it on an other one?

amarinediary
  • 4,930
  • 4
  • 27
  • 45
abbas derafshi
  • 307
  • 1
  • 11

2 Answers2

2

Loading scripts and stylesheet from the function.php file is the best practice with Wordpress.

Adding scripts and styles to WordPress is a fairly simple process. Essentially, you will create a function that will enqueue all of your scripts and styles.

Source @ https://developer.wordpress.org/themes/basics/including-css-javascript/

With Wordpress you can register a script and stylesheet before actually enqueuing it. We use some really handy functions called wp_register_script / wp_register_style for scripts and wp_enqueue_script / wp_enqueue_style for stylesheet. You should pay attention and read about the functions arguments

Together with some conditional tags and functions we end up building really complex behaviours to conditionally register and enqueue scripts and stylesheet on our theme and pages. You should pay attention and read about the functions arguments.

The Conditional Tags can be used in your Template files to change what content is displayed and how that content is displayed on a particular page depending on what conditions that page matches.

Source @ https://codex.wordpress.org/Conditional_Tags

For example is_home(), is_search(), is_single() or is_page()... can be used to conditionally register and enqueue scripts and stylesheet on our different pages.

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Register then enqueue jquery_js
    * @link https://developer.wordpress.org/reference/functions/wp_register_script/
    * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    */
    wp_register_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true );
    wp_enqueue_script( 'jquery_js' );
  };
}; ?>

In this example we only want to enqueue our jquery-3.5.1.min.js if we are on a different page than an admin's one, using if ( ! is_admin() )....


Register, Enqueue and CDNs

script and stylesheet can be hosted locally or on a different server (eg: CDNs). When using CDNs, we want to make sure that the source is available. We can use @fopen(); to make sure the CDN is reachable, and if not, serve a fallback:

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Register then enqueue jquery_js
    * @link https://developer.wordpress.org/reference/functions/wp_register_script/
    * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    *
    * Check if CDN's url is valid, if not return fallback
    * @link https://www.php.net/manual/en/function.fopen.php
    */
    $test_jquery_js = @fopen( 'https://code.jquery.com/jquery-3.5.1.min.js', 'r' );
    if( $test_jquery_js !== false ) {
      wp_register_script( 'jquery_js', '//code.jquery.com/jquery-3.5.1.min.js', array(), '3.5.1', true );
    } else {
      wp_register_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true );
    };
    wp_enqueue_script( 'jquery_js' );
  };
}; ?>

Adding Attributes (eg: Crossorigin, Integrity)

Sometimes it is required to add attributes to script and stylesheet tags, to properly enqueue them. Using the script_loader_tag or style_loader_tag hook, we can do just that:

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Register then enqueue jquery_js
    * @link https://developer.wordpress.org/reference/functions/wp_register_script/
    * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    *
    * Check if CDN's url is valid, if not return fallback
    * @link https://www.php.net/manual/en/function.fopen.php
    *
    * Add rel='preload' <link> and required attributes to jquery_js
    * Filters the HTML link tag of an enqueued style & add required attributes
    * @link https://developer.wordpress.org/reference/hooks/script_loader_tag/
    */
    $test_jquery_js = @fopen( 'https://code.jquery.com/jquery-3.5.1.min.js', 'r' );
    if( $test_jquery_js !== false ) {
      wp_register_script( 'jquery_js', '//code.jquery.com/jquery-3.5.1.min.js', array(), '3.5.1', true );
    } else {
      wp_register_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true );
    };
    wp_enqueue_script( 'jquery_js' );

    add_filter( 'script_loader_tag', 'data_jquery_js', 10, 3 );
    function data_jquery_js( $tag, $handle, $src ) {
      if( $handle === 'jquery_js' ) {
        $integrity = 'sha256...';
        $tag = str_replace(
          array(
            "<script",
            "></script>",
          ),
          array(
            "<link rel='preload prefetch' href='" . esc_url( $src ) . "' as='script' integrity='" . $integrity . "' crossorigin='anonymous' />" . PHP_EOL . "<script",
            "integrity='" . $integrity . "' crossorigin='anonymous' async></script>",
          ),
          $tag
        );
      };
      return $tag;
    };
  };
}; ?>

Here, we are adding a preload link tag, the crossorigin, integrity and the async attribute.


Always register?

If you don't need to register your script or stylesheet prior to enqueuing it, you can actually ignore it. eg:

wp_enqueue_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true  );

Here we don't register our script and jump straight to the enqueue.


jQuery already part of Wordpress core?

With Wordpress, jQuery is normally pre-registered, and comes with the core. If you want to enqueue your own version you MUST deregister the core jQuery version.

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Deregister Wordpress jquery core version
    * @link https://developer.wordpress.org/reference/functions/wp_deregister_script/
    */
    wp_deregister_script( 'jquery' );

    //...here goes the rest of your function...
  };
}; ?>

Enqueue and register a script or stylesheet on the admin side

Using the admin_enqueue_scripts action hook, you can do just that.

<?php
do_action( 'admin_enqueue_scripts', 'admin_scripts' );
function admin_scripts() {
  //...here goes the rest of your function...
}; ?>

Learn more

amarinediary
  • 4,930
  • 4
  • 27
  • 45
1

You could add an if statement to your <head> in header.php.

<?php if (is_page($id)) { ?>
#css or js here
<?php } ?>

Replace $id with the ID or slug of the page you want to load the <script> or <style> on.

John Fotios
  • 130
  • 9