0

I have this in my main plugin file (/plugins/oglasi/oglasi.php)

<?php
 /*
 Plugin Name: Oglasi
 Plugin URI: 
 Description: Custom post type "Oglasi".
 Version: 1.0
 Author: Dragi
 Author URI:
 License: GPLv2
 */

function james_adds_to_the_head() {
    wp_register_script( 'add-bx-js', plugin_dir_url( __FILE__ ) . 'js/filter-oglasi.js', array('jquery'),'',true  ); 
}

add_action( 'wp_enqueue_scripts', 'james_adds_to_the_head' );

And here /plugins/oglasi/js/filter-oglasi.js I have:

jquery(document).ready(function() {

    console.log("MAIN IS LOADED");
    alert("Dragi");
});

but it is not working. Can someone help?

1 Answer 1

1

wp_register_script() registers a script to be enqueued later using the wp_enqueue_script() function. Use wp_enqueue_script('add-bx-js') to load registered script. This means, if you want to register your scripts, but not directly load them in your pages, you can register the files once, and then load them when you need them.

Use the following code :

function james_adds_to_the_head() {
    wp_register_script( 'add-bx-js', plugin_dir_url( __FILE__ ) . 'js/filter-oglasi.js', array('jquery'),'',true  ); 
    wp_enqueue_script( 'add-bx-js' );
}

add_action( 'wp_enqueue_scripts', 'james_adds_to_the_head' );

or :

function james_adds_to_the_head() {
    wp_enqueue_script( 'add-bx-js', plugin_dir_url( __FILE__ ) . 'js/filter-oglasi.js', array('jquery'),'',true  );
}

add_action( 'wp_enqueue_scripts', 'james_adds_to_the_head' );

more info :

https://wordpress.stackexchange.com/questions/82490/when-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque

https://developer.wordpress.org/reference/functions/wp_register_script/

Update

You have error in your js file. Use jQuery instead of jquery as follow and then use CTRL+F5 to force refresh browser cache. Also you can use wp_register_script() fourth parameter - version parameter - to force refresh assets.

jQuery(document).ready(function() {

    console.log("MAIN IS LOADED");
    alert("Dragi");
});
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, but it is still not working. I still can see the message in the console, or the alert. This can work if a put the code in the theme's functions.php file, but I want to do this in the plugin. Any other thought? Thank you.
wp_enqueue_script() works in both themes and plugins. Check your browser console for 404 or 403 error and search your file name in browser page source.
Check answer update. Code tested and works properly.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.