0

I would like to run a javascript function when jQuery is ready. This doesn't work:

wp_enqueue_script('jquery');
?>
<script>
    (function() {
        doJQstuff()
    })();
</script>

Any ideas?

wp_localize_script( 'search-ajax', 'search_ajax_object',
    array( 
        'url' => admin_url( 'admin-ajax.php' ),
    )
);
wp_enqueue_script( 'search-ajax', get_template_directory_uri() . '/js/search-ajax.js', array('jquery'), null, true );

search-ajax.js

console.log(search_ajax_object) //-> Uncaught ReferenceError: search_ajax_object is not defined
7
  • You should load your script via wp_enqueue_script() as well, not output it directly in the template. Have you tried that?
    – kero
    Commented Jan 27, 2022 at 12:44
  • @kero Can you enqueue javascript functions that use php calls inside of the function body?
    – Fluxian
    Commented Jan 27, 2022 at 12:56
  • No, that is usually bad practice. Either use wp_localize_script() to pass data from PHP to JS or query the REST/ajax endpoints from JS.
    – kero
    Commented Jan 27, 2022 at 13:05
  • @kero I can't get that to work. Can you check the updated question and see what's wrong? :D The object is not accessible from the javascript
    – Fluxian
    Commented Jan 27, 2022 at 14:04
  • 1
    @kero Ah, yeah that works.
    – Fluxian
    Commented Jan 27, 2022 at 14:10

1 Answer 1

1

You can't do that way

first you need to enqueue your script using :

wp_enqueue_script('jquery');
wp_enqueue_script('ns-likes-dislikes-for-posts-js', plugin_dir_url(__FILE__). 'path/to/your/js/file/from/plugin/directory/custom.js', array('jquery'), '1.0', true);

in custom js start writing your js with jquery but you can't use $, instead use jQuery.

if you want to use $ instead of jQuery try this code:

(function($){
  // enjoy jquery with $('selector')
})(jQuery)

first you need to enqueue script then you can localize it.

wp_enqueue_script( 'search-ajax', get_template_directory_uri() . '/js/search-ajax.js', array('jquery'), null, true );
wp_localize_script( 'search-ajax', 'search_ajax_object',
    array( 
        'url' => admin_url( 'admin-ajax.php' ),
    )
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.