• hedgerh

    (@hedgerh)


    What’s the best way to get/set an option from within an enqueued JS script?

    My best guess to set is to create a WP REST Route that sets/updates the option. I saw an SO answer from 2013 that said I could send a POST to admin-ajax.php to a handler I define, but I’m not sure if that’s out of date, or which is preferable.

    For getting an option, should I use wp_localize_script/wp_add_inline_script? Is it worth setting up another REST endpoint to fetch the option?

    Thank you!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Ajax methods are still completely valid. The API approach offers more validation options and is a more structured approach, hence by some reckoning the preferred approach. However, if the user is going to be logged in with adequate capability anyway, Ajax is more straight forward and to the point. It’s a perfectly valid approach.

    Localize and inline script essentially do the same thing. Since wp_localize_script() directly relates to the script being enqueued, IMO it’s the preferred approach when your script is in an external file. If your entire script were fairly simple where it’s hard to justify an external file, then use wp_add_inline_script().

    You could get option values through the API. It might be a reasonable approach if the desired option can’t be known when the page is first served. But if it can be fetched in PHP and passed through localize script, you’d avoid an additional API request, which is worth something of itself.

Viewing 1 replies (of 1 total)

The topic ‘Plugin Dev: update_option from JS script?’ is closed to new replies.