1

Ok, so we know Wordpress comes with a built in search form. However, I've created a custom archive page that lists posts from a specific post type. I would like to integrate a search box that only searches for posts related to that specific post.

I see a lot of people approaching this in several ways but no working examples. Any ideas how I could get this done?

Thanks!

2

To enable search on a custom post type archive, I use the pre_get_posts hook. Add this code to your theme functions.php file. Here is an example of enabling search on a post type called "resource":

// Enable resource search
    add_action('pre_get_posts','pk_enable_resource_search', 1000);
    function pk_enable_resource_search( $query ) {

        if ( $query->is_archive('resource') && $query->is_main_query() && ! is_admin() ) {

            $search = ! empty($_GET['rs']) ? $_GET['rs'] : false;

            //Check for custom search
            if($search) {
                $query->set( 's', $_GET['rs'] );
            }
        }
    }

Then on the archive page, you'll need to set up your search form:

<form class="archive-resource__search-form" action="<?php echo get_post_type_archive_link('resource'); ?>">
            <input type="text" placeholder="Search Resources" value="<?php echo $search_term; ?>" name="rs">
            <button type="submit" class="far fa-search"></button>
</form>

Lastly, don't forget to look for and set your search term on your archive page. Add these variables to the top of your search form template part/archive template:

$is_search   = ! empty( $_GET['rs'] ) ? true : false;
$search_term = $is_search ? $_GET['rs'] : '';
0

You can edit the search form redirecting it to your custom archive page. Then, in the custom archive page code, you can detect when a search is triggered (either with $_POST or $_GET) and change the main query to include the search term. Something like this:

Searchform:

<form method="GET" action="<?php echo get_post_type_archive_link( $post_type ); ?>">
    <input name="s" type="text">
    <input type="submit">
</form>

Archive:

<?php
if (isset($_GET['s'])
    query_posts('s='. $_GET['s']);

while ( have_posts() ) : the_post();
    //do stuff
endwhile;
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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