L
L
Light7772018-04-25 20:06:26
WordPress
Light777, 2018-04-25 20:06:26

How to add js code snippets to Wordpress?

Hello!
How to add pieces of code to WordPress of such a plan (not through the admin panel)?

<script type="application/x-javascript">
 addEventListener("load",function() { setTimeout(hideURLbar, 0); }, false);
 function hideURLbar(){ window.scrollTo(0,1);}
</script>

<script type="text/javascript">
  jQuery(document).ready(function($) {
    $(".scroll").click(function(event){		
      event.preventDefault();
      $('html,body').animate({scrollTop:$(this.hash).offset().top},1000);
    });
  });
</script>

There are pieces both in the footer and in the header, how to add everything correctly? Regular js files added to functions.php like this (below) and they work<script>
wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js');	
  wp_enqueue_script( 'easing', get_template_directory_uri() . '/js/easing.js');	
  wp_enqueue_script( 'jarallax', get_template_directory_uri() . '/js/jarallax.js');

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Syomka Gavrilenko, 2018-04-25
@Light777

There are 2 options:
1) Through the template file. Just open the template files and edit. Please note that after updating the theme, all changes will be overwritten.
2) Via hooks from a plugin or child theme
Code example:

add_action('wp_head','cema93_faq_hook_js');
 
function cema93_faq_hook_js()
{
 
$output="
// тут может быль любой код
<script type=\"text/javascript\">
$('document').ready(function(){
  $('div[id^=cat-]').next('div[id^=cat-o-]').hide();
  $('div[id^=cat]').click(function() {
    $(this).next('div[id^=cat-o-]').toggle();
    $(this).next('div[id^=cat-o-]').children('div[id^=o-]').toggle();
  });
  $('div[id^=q-]').click(function() {
    $(this).next('div[id^=o-]').toggle();
  });
});
 
</script>
//а тут он заканчивается
";
 
echo $output;
}

You can read more about this at the link https://site-style.by/dobavlyaem-proizvolnyj-kod-v...

C
Cyril, 2018-04-25
@cyril_b

paste the code in header/footer

M
Max Medar, 2018-04-25
@MedVedar

You can use wp_footer , wp_head hooks . If you need to take into account dependencies on other scripts, then it is better to use wp_add_inline_script()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question