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.
echo '<script>jQuery(document).ready(function(){redirectToHome();});</script>';and check the functions are defined before the place you call