skip to Main Content

I have a basic bunch of CSS/Js files defined in my functions.php file. There I register and enqueue those scripts and stylesheets.

But in specific situations I want to load additional scripts based on the site template which is used.

I tried to register and enqueue those additional scripts in the specific template file, but it didnt work. It does only work when included in the functions.php.

What is the correct way to do this?

2

Answers


  1. add this to your functions.php in child theme:

    add_action(
        'wp_enqueue_scripts',
        'loadActionFrontend'
    );
    
    
    function loadActionFrontend()
    {
        if( is_page( 'pageid here' ) ) {
            wp_register_script(
                'scriptName',
                'scripturl',
                [],
                '',
                true
            );
    
            wp_enqueue_script('scriptName');
        }
    }
    

    with the query if( is_page( 'pageid here' ) ) you can insert your desired pageid where the script shold loaded.

    Login or Signup to reply.
  2. You can try like this

    add_action( 'wp_enqueue_scripts', 'enqueue_file' );
     
     function enqueue_file() {
      if(is_front() || is_archive()){ // you can set here condition
          wp_enqueue_style( 'main-css', get_template_directory_uri() . 
          '/static/css/main.min.css"' ); 
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search