Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #309330

    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.

    • This topic was modified 10 years, 2 months ago by Ismael.
    #309436

    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

    #309539

    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

Viewing 3 posts - 1 through 3 (of 3 total)
  • The topic ‘Using conditions in functions.php’ is closed to new replies.