Run Specific Js on Specific page Wordpress

2020-02-24 04:59发布

问题:

I want to run a specific js on a specific page. I.e: wwww.custom.com/english/

I've tried the following two codes (header.php and functions.php) but none of them work.

Code 1:

<script>
if(location.pathname=="/english/") 
 script.src = /js/custom.js;
</script>

Code 2:

function my_scripts() {
    if( is_page( array( 'about-us', 'contact', 'management' ) ){
        wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
    }
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );

The header one does not show at all, no error either. The functions.php is a syntax error.

Any suggestions? Much Obliged

PS: I'm using WordPress.

回答1:

You code is great! You are just missing a closing parenthesis:

function my_scripts() {
    if( is_page( array( 'about-us', 'contact', 'management' ) ) ){
        wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
    }
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );

For future reference, in your wp-config.php file you can set debug to true, I believe that this will pick it up.



回答2:

There is multiple other ways.

Just open your header.php and try to get current page slug or id and put simple if condition it will surely include your js

Code 1

global $post;
$post_slug=$post->post_name;
if($post_slug == 'about'){
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
}

OR Code 2

$currentID= get_the_ID();
//instead of 10 put the your id
if($currentID == 10){
 <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
}