Ahmed ElSayed Ahmed ElSayed - 7 days ago 4
Javascript Question

Using wp_enqueue in Wordpress

I turn to this awesome community , after days of trying to fix this bug, my problem is really simple, but it has got to me. I am trying to enqueue a Java script to my Theme my login Plugin while using the evolve theme.

here is the code snippet that does that, and i used the global function to check if the function is being loaded , and it is not being loaded. 'a' does not change to true.

For some reason it looks like 'wp_enqueue_scripts is not working. I have tried to also add wp_head() with no luck.



<?php
$GLOBALS['a'] = 'false';
add_action( 'wp_enqueue_scripts', 'load_location' );

function load_location() {
$GLOBALS['a'] = 'true';
wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
wp_enqueue_script('load_location_test');
}

?>
<?php echo $GLOBALS['a'] ?>;





Thanks in advice

The link is http://www.meetntrain.com/register

Answer

So, for your enqueue to work, you need to add the code in your functions.php file or in your plugin.

add_action( 'wp_enqueue_scripts', 'load_location' );

function load_location() {
    wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
    wp_enqueue_script('load_location_test');
}

This will add the JS file to all your pages. If you want to target a specific page, you can either do it via JavaScript or directly in your PHP file.

If your theme uses body_class(), you can target that specific page by the class. You should then wrap your JS like:

if( $('body.classUsed').length ){
// Your JS code here
}

Note that the file will still be enqueued all the time. Alternately, if you want to add the JS file only to a specified page, you can wrap it in an is_page() condition:

add_action( 'wp_enqueue_scripts', 'load_location' );

function load_location() {
    if( is_page('your-page') ){
       wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
       wp_enqueue_script('load_location_test');
    }
}