hi!
I’m trying to load custom js individually per page in my functions.php child theme.
My intention was to use something like
$values = get_post_custom_values( 'custom_field' );
if ( get_post_custom_values( 'custom_field' ) ) {
wp_register_script( 'myscript', get_stylesheet_directory_uri().'/js/myscript.js', array('jquery'), "4", false);
wp_enqueue_script( 'myscript' );
}
– or –
if ( is_page( array("title-slug") ) ) {
wp_register_script( 'myscript', get_stylesheet_directory_uri().'/js/myscript.js', array('jquery'), "4", false);
wp_enqueue_script( 'myscript' );
}
It’s doing fine without the condition, but then I get tons of JS in all other pages as well.
Do I miss something?
Appreciate your help.
Hey Fritz!
We aren’t really able to debug custom code for users. The best place to get assistance with that would be the WordPress forums or http://wordpress.stackexchange.com/
Best regards,
Devin
Found the following statement in http://codex.wordpress.org/Conditional_Tags :
“…For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function..”
So the solution is to place the condition INSIDE a function and NOT directly in functions.php. The following code snippet works:
function register_myscripts() {
if(is_page( ::pageid:: )) { // needs to be INSIDE the function
$child_theme_url = get_stylesheet_directory_uri();
wp_register_script( 'myscript_name', $child_theme_url.'/js/myscript.js', array('jquery'), "4", false);
wp_enqueue_script( 'myscript_name' );
}
}
add_action('wp_enqueue_scripts', 'register_myscripts', 100);
regards, fri_z