Searching post types

Is it possible to take a user input from a search form, use that to search a custom post type via the WP_Query class and then redirect the user to a page template to display the results?

For example,

Assume you have a search input that takes city, state or zip You then enter in California, next that input is then captured and the WP_Query is used to then search custom post type "Locations". It finds 4 locations matching, you are then redirected to page "Locations" which then displayed all 4 locations.

How would you do this?

Note: This is not a home work assignment, this a client feature. Yes there are plugins but due to how this is customized and how they want it laid out, it has to be built from the ground up.

Topic wp-query location-search theme-development custom-post-types Wordpress search

Category Web


The quick and simple method might be to create a custom page template and have the search form send the user to the page that you create with it.

<?php
/* 
Template Name: Location Results
*/
if ( isset($_REQUEST['search_field_name']) && !empty($_REQUEST['search_field_name']) ) {
    # Read and escape the input data
    # Do your query, grab your results
    # Display your results to the user
} else {
    # No results found. Display search form again with note to enter something.
}

You could then create a new page, selecting this page template and edit your form to send the results to it.

There are other ways to do this, but this is a fairly quick and easy method that I use now and again.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.