Using next/previous_posts_link with customised search

You don’t need the type variable and other bits of custom search query code, or custom functions like the other answers.

In your searchbox, instead of submitting the form to / submit it to /my_post_type/ instead! WordPress will handle all the rest for you automagically, with no effort involved.

What’s more this means all the usual functions will work just as you expected them to!

For example, instead of:

example.com/?type=species&s=giraffe

You can do:

example.com/species/?s=giraffe

Where example.com/species is your custom post type archive page.

And for your Species specific search box:

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/species/' ); ?>">

If you’d like a single searchbox with a choice, you can change the home_url function parameter from ‘/species/’ to “https://wordpress.stackexchange.com/”, then add a dropdown box field whose name is ‘post_type’ containing the different values you desire e.g.:

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/species/' ); ?>">
    <select name="post_type">
      <option value="">Sitewide</option>
      <option value="species">Species</option>
      <option value="Glossary">Glossary</option>
    </select>

Doing it this way means no custom queries, and no faffing around with variables. All the functionality is provided out of the box by WordPress, and the only extra part you need to do is change your searchbox html!

All the normal wordpress functions on archive pages will now work as expected with no additional steps

You can use the same trick with categories, tags, taxonomies, author and date archives.

So remove the WP_Query in your search templates, and remove the extra code you put above the get_template_part line in search.php, change your search box, and make sure custom permalinks are activated

Leave a Comment