0

So I guess the question is : How do I define new page/url to which I can pass custom parameters, do a search for custom post type and pass the results to custom template for rendering?

I have made a custom post type Apartment. Apartments have occupied dates recorded in the database and I want users to be able to search for free apartments between two dates.

I know how to do the search algorithm but I don't know what is the best way to define a new search page with custom parameters in WordPress.

And I'd also like to avoid writing the search algorithm in the template file if possible.

URL should look something like this:

  • mysite.com/find/begin-date/end-date
  • concrete example : mysite.com/find/2018-03-05/2018-03-10

But it is also OK if it looks something like this as well:

  • mysite.com/find?begin=2018-03-05&end=2018-03-10

1 Answer 1

1

Add this code in functions.php

function custom_rewrite_rule() {

    //Initializing Rewrite Tags
    add_rewrite_tag('%begin-date%', '([^&]+)');
    add_rewrite_tag('%end-date%', '([^&]+)');
    add_rewrite_tag('%offset%', '([^&]+)');

    //Find page rewrite rules
    add_rewrite_rule('^find/([^/]*)/([^/]*)/([^/]*)/?','index.php?page_id=<SEARCH_PAGE_ID>&begin-date=$matches[1]&end-date=$matches[2]&offset=$matches[3]','top');
    add_rewrite_rule('^find/([^/]*)/([^/]*)/?','index.php?page_id=<SEARCH_PAGE_ID>&begin-date=$matches[1]&end-date=$matches[2]','top');

    flush_rewrite_rules();
}
add_action('init', 'custom_rewrite_rule', 10, 0);

On your custom search page template

$begin_date = get_query_var('begin-date');
$end_date   = get_query_var('end-date');
$offset     = get_query_var('offset') ? get_query_var('offset') : 1;

Create a page having slug find and apply a custom page template over it .. replace <SEARCH_PAGE_ID> with the newly created page ID and update the permalink structure!

Use these values in your custom query in the page template! :)

This code will render the URL as per your desired structure!

  • mysite.com/find/begin-date/end-date
  • mysite.com/find/begin-date/end-date/offset (if you need pagination to be enabled)

In case you want the second option .. you can simply use the following code over your find page template and everything will work!

$begin_date = $_GET['begin'];
$end_date   = $_GET['end');
$offset     = $_GET['page'] ? $_GET['page'] : 1;
  • mysite.com/find?begin=2018-03-05&end=2018-03-10
  • mysite.com/find?begin=2018-03-05&end=2018-03-10&page=2
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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