简体   繁体   中英

wordpress calling javascript function in plugin

i'm struggling with a way to make javascript calls from within my wordpress plugin. I have an external javascript file with different functions in it that i'd like to be able to call individually and whenever i need them.

in my main plugin file i register and enqueue the javascript file.

wp_register_script( 'pluginMain', plugins_url( '/js/pluginMain.js', __FILE__ ) ); wp_enqueue_script( 'pluginMain' );

inside the pluginMain.js file i want to put several different functions, and call them when needed on different pages in the site. an example is this redirect function.

function redirectToHome() {
alert( 'Something went wrong.  You are being redirected home.' );

window.location.replace("https://somemainpage.com");
}

the only way i can figure out how to make anything happen is to add the below code to the javascript file. but then it runs any time after the file has been enqueued, so everywhere.

jQuery (document).ready (function () {
redirectToHome();
});

i tried adding the jQuery (document) code to the html of a page and removing the jQuery (document) code from the javascript file, but then nothing ever happens.

echo '<p>Something has gone wrong.  You are being returned to the main page</p>';

    echo '<script type="text/javascript">
    <!--
    jQuery (document).ready (function () {
    redirectToHome();
    });
    //-->
    </script>';

i'm obviously new to this, and pretty confused as to where to go from here. can i get some guidance? thanks.

If you only need to run the script in certain situations, you want to do something like this:

wp_register_script( 'pluginMain', plugins_url( 
'/js/pluginMain.js', __FILE__ ) );

This will register, but not load the script until you do an enqueue. You could then do this:

add_action('loadmyscripthereplz', 'somefunction');
function somefunction(){
   wp_enqueue_script('pluginMain');
}

And then, wherever you want the script to load, eg a page template, just do:

do_action('loadmyscripthereplz');

This would allow you to literally place the script call anywhere you want. Alternatively, you could just register the script in your function file like you have done, and conditionally call the wp_enqueue_script('script') with checks like is_front_page() or whatever other WP checks you need. This will allow you to choose where and when the script loads as well.

As an aside, please ensure that you're doing proper checks/validations when doing redirects, as this could potentially be a security hole.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM