0

I'm developing a widget. Its form has two HTML select elements: one to display a list of all categories, and the other for displaying a list of posts based on the selected category.

The posts HTML select element depends on the selected category to show a list of posts. That works fine. The problem is I must save the widget after selecting a category in order to populate the posts select element with the posts of the selected category.

How can I populate the posts select element as soon as I choose a category from the category select element, without the need of clicking the save button?

1

You're going to want to use AJAX for this. Wordpress provides resources for connecting JS to PHP callbacks which is outlined in detail in the Codex. Basically, you'll want to take the following steps:

  1. Attach a handler to the first category select box using the .change() jQuery method.
  2. Use an AJAX function to post that data to the ajax url to call your PHP callback function.
  3. Create a PHP callback function that will take the category name from the select box and use WP_Query to retrieve a list of posts, which the function will then return to the AJAX function.
  4. Take the server response back in the JS ajax function and use it to set the select values of the second select box in the widget using jQuery.

It sounds like you've already figured out the complexity of the Widgets API so this should be a walk in the park for you.

  • That is very helpful thank you. this way was in my mind to go with, but I thought that may be a more official way to do that, also i thought to trigger the event attached to the save button when a category is selected so that the posts select element will receive the new selections. Any way I'll go with the approach you suggested. Thank you agin – Omar Ali May 20 '15 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.