I am creating my first ever plugin, as I am not a programmer, I have been following tutorials and reading the codex, etc.
My plugin consist in showing a notice to users when certain conditions are met, I have written it in jQuery and placed it in a js file which is enqueued by the plugin along with styles.
I have followed a tutorial that simply ads a settings page and a form with a simple text box to save data in the wp options table, I tested and it worked, the data was stored successfully.
How do I now transfer the data from the wp options to my js file, the line where the notice is display is;
jQuery('.notice_container').wrap(<'div id="custom_notice"><span>Hello World....</span></div>')
Thank you for your time.
Assuming you’re not using AJAX for form submission, you can use
wp_localize_script()
. Here’s a simplified version:In your plugin file:
contents of
myjs.js
file:wp_localize_script()
will add a global variable calledjsLocalizedObject
to your document’s<head>
. IF you view the source of your page, you’ll see something like:To get a value from your
wp_options
table, you can useget_option()
and then pass the result instead of thehello world
in thewp_localize_script
function.Your code would then look like:
and your jQuery part:
Note that you should use
admin_enqueue_script
instead if your JS should load in the dashboard.