Conditional Tags in Wordpress: How to Run a Different JS File Depending on Page ID or Title
I want to run a different external JavaScript file for each WordPress page, depending on the page ID.
If Page ID is [1], run somescr开发者_开发百科ipt.js if Page ID is [15], run someotherscript.js if Page ID is [195], run yetanotherscript.js
if default, run defaultscript.js
Could someone please show me how this is done in WordPress with Conditional Tags?
Best regards,
Dimitri Vorontzov
You should NEVER echo script call to the header. Your going to break plugins screw up the dependencies and load multiple copies of scripts if you do it that way.
Create a function in functions.php
add_action( 'init', 'dim_load_scripts' );
function dim_load_scripts() {
wp_register_script( 'my-first-script', get_bloginfo( 'stylesheet_directory' ). '/path/to/script.js', array( 'jquery' ), true);
//the jquery is only needed if it is a depencency
wp_register_script( 'my-second-script', get_bloginfo( 'stylesheet_directory' ). '/path/to/script.js', array( 'jquery' ), true);
wp_register_script( 'my-third-script', get_bloginfo( 'stylesheet_directory' ). '/path/to/script.js', array( 'jquery' ), true);
wp_register_script( 'my-fourth-script', get_bloginfo( 'stylesheet_directory' ). '/path/to/script.js', array( 'jquery' ), true);
if (is_page( 22 ) ) {
wp_enqueue_script( 'my-first-script' );
} elseif
(is_page ( 33 ) ) {
wp_enqueue_script( 'my-second-script' );
} elseif
(is_page ( 33 ) ) {
wp_enqueue_script( 'my-third-script' );
} else
if (is_page ( 33 ) ) {
wp_enqueue_script( 'my-fourth-script' );
}
}
The code in your comments had syntax errors. Corrected:
function dim_load_scripts() {
wp_register_script( 'homescript.js', get_bloginfo( 'stylesheet_directory' ). '/supersized/js/homescript.js', array( 'jquery' ), true);
wp_register_script( 'defaultscript.js', get_bloginfo( 'stylesheet_directory' ). '/supersized/js/defaultscript.js', array( 'jquery' ), true);
if (is_home() ) {
wp_enqueue_script( 'homescript.js' );
} elseif(is_page ( 11 ) ) {
wp_enqueue_script( 'defaultscript.js' );
}
}
Also this has to be in functions.php. I won't work in wp-header.php
Having tried the suggested solutions, I couldn't make them work. I'm sure Chris's advice is perfectly solid and it's me who's doing something wrong, but so far I had to resort to a duct tape solution:
I created a custom page template for every version of the script I wanted to run, and assigned a separate template to each page. Not the most elegant solution, but it works.
精彩评论