Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Specific Js on Specific page Wordpress

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.

like image 804
Project Orbit Avatar asked Sep 03 '17 02:09

Project Orbit


People also ask

Can I code JavaScript in WordPress?

JavaScript can be used within the WordPress platform to add dynamic elements to pages and posts, or across your entire website.

How do I enqueue a script in WordPress?

To enqueue scripts and styles in the front-end you'll need to use the wp_enqueue_scripts hook. Within the hooked function you can use the wp_register_script() , wp_enqueue_script() , wp_register_style() and wp_enqueue_style() functions.


1 Answers

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.

like image 196
Siegfried Grimbeek Avatar answered Oct 21 '22 22:10

Siegfried Grimbeek