• callherzino

    (@callherzino)


    Hi, I’m working on a project where users select their current “mood” from a list of checkboxes on a form, and I want the results page to show blog posts tagged with those selected moods.I’m using custom HTML for the form and PHP (via shortcode). I’ve tried some code, but the results page shows nothing.What’s the best way to pass selected checkbox values, to a results page and display matching posts?I’d appreciate any help, ideas, or working examples. Thanks in advance!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    The form and the results can all be managed through a single template, pattern, or shortcode. Have the form POST any user selections. If the request is a POST method, process the form data and use it to create a custom WP_Query object that can output the results from user selections. If the request is a simple GET request, simply output just the form without running any query or showing results.

    When the form data is POSTed, any selected names and values will be in the passed array. Unselected elements will not be in the data at all. If you will qualify the posts query by tags, I recommend assigning the related tag ID as form field values. Then it’s easier to turn form data into query vars. Collect all the passed IDs into a simple indexed array. If you set up the form well, the passed array might already be in the correct structure. Even so, you should validate and sanitize form data before using it in a query.

    With an array of tag IDs, depending on whether you want to logically AND or OR the tags, assign the tag ID array to either the tag__and or tag__in query vars. Then instantiate the WP_Query object and run The Loop as we normally would.

    If you really want to use a shortcode for this, you need to capture all output in an output buffer. You cannot directly run the usual loop from a shortcode handler since it generates output at the wrong time. At then end of your shortcode handler, return and clean the buffer contents.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.