Home > other >  Add js in wordpress pages except some of them?
Add js in wordpress pages except some of them?

Time:01-21

I wrote a code to add a js to specific pages in wordpress. but if I want to:

1- run the code in specific pages how can I change the code?
2- or run the code in everywhere except in some page IDs?
how can I cahnge that?

thanks in advance to everyone! :D

function wpb_hook_javascript() {
  if (is_page ('727')) { 
    ?>
        
<script type="text/javascript">
my script
</script>
    <?php
  }
}
add_action('wp_head', 'wpb_hook_javascript');

CodePudding user response:

This is for 1:

if (is_page (array(727, 934))) { 
    // code here...
}

This is for 2:

if (!is_page (array(727, 934))) { 
    // code here
}

CodePudding user response:

I think this would be as easy as

function wpb_hook_javascript() {
    if (!is_page(array('the', 'excepted', 'pages'))) {
        wp_enqueue_script('script_name', 'script_path.js')
    }
}

add_action( 'wp_enqueue_scripts', 'wpb_hook_javascript' );

I used wp_enqueue_script because I like it more, but obviously you can stay with injecting it into the head directly, depending on what it does.

Edit: Pretty sure it would work like this:

add_action( 'wp_head', function() {
  if (!is_page(array('the', 'excepted', 'pages'))) {
    ?>
      <script type="text/javascript">
        my script
      </script>
    <?php
  }
}

Compare logical operators in php, is_page, arrays in php and wp_enqueue_script.

  • Related