简体   繁体   中英

Add Javascript code to a template page in Wordpress

I would like to use this Grid Column Carousel . I have added some code in functions.php because I would like this carousel to be only on some pages. So it requires to include a js file which load on my homepage, but also this piece of code :

<!-- Include the script--<
<script src="js/GridColumnCarousel.js"></script>

<!-- initialize the carousel -->
<script>
  window.onload = function() {
    var options = {
      elem: document.getElementsByClassName('example-1')[0],
      gridColClasses: 'col-xs-12 col-sm-6 col-md-4 col-lg-3'
    };

    var gCCarousel = new GCCarousel(options);      
  };
</script>

How do I add it only on my page-custom.php ?

My code in functions

add_action('wp_enqueue_scripts','load_js_slider');
    function load_js_slider(){
        if ( is_page_template('accueil_page.php') ) {
            wp_enqueue_script('slider_script', get_template_directory_uri() . '/js/GridColumnCarousel.js');
            wp_enqueue_script('slider_script', get_template_directory_uri() . '/js/slider.js');
        }
    }

Thank you

You can add to your page-custom.php some container like:

<div class="carusel"></div>

And in your javascript code check if this element exist - execute your code. Something like this:

<script>
  window.onload = function() {
    if(document.getElementsByClassName('carusel')[0].length > 0) {
    var options = {
      elem: document.getElementsByClassName('example-1')[0],
      gridColClasses: 'col-xs-12 col-sm-6 col-md-4 col-lg-3'
    };

    var gCCarousel = new GCCarousel(options);  
   }    
  };
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM