I have a Custom Post Type called “cars” that stores several custom fields along with the standard Title/Description fields. I need users to be able to search through the CPT based on the custom fields matching the user’s criteria. I figured that part out and it works, but the problem is pagination. I figured out how to paginate the CPT based on code I found on Google, and it works, but once you leave page 1, you no longer have the search data submitted with the form. I just need to know how I should store this or pass it along.
In regular PHP I would just use a session to store the data, but I’ve been told not to do that with WordPress. So, what is the best option? I’ve been told Transients are the WP version of sessions, but I’m not sure how to efficiently use them for this and how to keep them separate for each user.
I’m not asking for anyone to write this for me — I just need some help understanding the best concept for this.
Instead of implementing a custom search query, instead include the custom fields in the standard search, and use rewrite rules to map
/?post_type=cars&s=mysearchterm
to/search/cars/mysearchterm
. Or just use the query vars in the URL rather thanPOST
/$_POST
or transient data.GET
/$_GET
is your friend here.Transients are intended for storing data temporarily rather than recalculating it, e.g. RSS feeds, and other things that are expensive to calculate that may not have a permanent lifetime. They are not a replacement for sessions ( nor should you need sessions or some other analogue ).
This should show you how to bundle the custom fields in the search:
http://stv.whtly.com/2010/03/15/extend-wordpress-search-to-include-custom-post-meta/
Test against
$wp->query_vars['s']
orget_query_var( 's' )
to see if your search query is for your post type so you can then conditionally include the custom meta search bits.credits: thanks kaiser for the get_query_var tip
Much like
@TomJNowell
answer.With your search, use
$_GET
instead of$_POST
for your search request. Your search variables will carry on from page to page in the URL for your custom pagination.Using
$_GET
is potentially asking for a security breach. Make sure you validate or sanitize your variables. WordPress has a great deal of documentation on Data Validation. Otherwise, read the PHP manual for more methods of Validation or Sanitization.As far as your custom pagination goes, I would recommend setting an extra variable in your URL. I’m sure your custom pagination already sets a page number. So you could obtain the page number from your URL, (e.g.
$_GET['page']
) and adjust your query offset for the search results.Hypothetically let’s say you had a URL-friendly pagination, along with the following configuration.
You could use the above code for your custom pagination to return the proper search results. Note: Remember, you would need to of course pluck out the search variables from the URL, to properly query the correct search results.