Best approach to fetch data from wp options to js file or php file

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.

Read More

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.

Related posts

1 comment

  1. Assuming you’re not using AJAX for form submission, you can use wp_localize_script(). Here’s a simplified version:

    In your plugin file:

    function wpse105919_add_scripts(){
      wp_enqueue_script( 'myjs', plugins_url( '/myjs.js', __FILE__ ) );
      wp_localize_script( 'myjs', 'jsLocalizedObject', 'hello world');
    }
    add_action('wp_enqueue_scripts', 'wpse105919_add_scripts');
    

    contents of myjs.js file:

    alert( jsLocalizedObject );
    

    wp_localize_script() will add a global variable called jsLocalizedObject to your document’s <head>. IF you view the source of your page, you’ll see something like:

    <script type='text/javascript'>
    /* <![CDATA[ */
    var jsLocalizedObject = "hello world";
    /* ]]> */
    </script>
    

    To get a value from your wp_options table, you can use get_option() and then pass the result instead of the hello world in the wp_localize_script function.

    Your code would then look like:

    function wpse105919_add_scripts(){
      wp_enqueue_script( 'myjs', plugins_url( '/myjs.js', __FILE__ ) );
      $myoption = get_option('option_name', 'default_value');
      wp_localize_script( 'myjs', 'jsLocalizedObject', $myoption);
    }
    add_action('wp_enqueue_scripts', 'wpse105919_add_scripts');
    

    and your jQuery part:

    jQuery('.notice_container').wrap(<'div id="custom_notice"><span>' + jsLocalizedObject + '</span></div>')
    

    Note that you should use admin_enqueue_script instead if your JS should load in the dashboard.

Comments are closed.