最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Creating a custom search for a specific post type

programmeradmin1浏览0评论

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!

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!

Share Improve this question asked Nov 9, 2015 at 19:48 JohannJohann 8674 gold badges14 silver badges31 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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'] : '';

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;
?>
发布评论

评论列表(0)

  1. 暂无评论