How to use wp loop in search.php

How to segregate product and post in search.php

I want to get the result in search.php include posts and products only, and the posts list will be display in POST tab, Products list in PRODUCT tab. I tried to use this code for loop but it get all posts and products:

<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
       <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php endwhile;?>
<?php endif; ?>

1 answer

  • answered 2019-11-22 18:22 Joel M

    You may want to try adding a post_type argument to the URL.

    www.example.com?s=test&post_type=product (shows products)

    www.example.com?s=test&post_type=page (shows pages)

    This is not exactly what you are asking because this is 2 separate pages (not 1 page with 2 tabs). You can add a hidden input field to a form in order to have the browser automatically append the post type to the URL. Ie.

    <form method="get" action="<?= get_bloginfo( 'url' ); ?>">
        <input type="hidden" name="post_type" value="product">
        <input type="text" name="s" value="<?= get_search_query(1); ?>" placeholder="Search Products...">
        <button type="submit">Go</button>
    </form>
    

    To show 2 tabs on the same page, you can use search.php and ignore the main query, and simply write two of your own queries by accessing $_GET['s'] (the function, get_search_term(), also accesses $_GET['s'] but can also sanitize it). Alternatively, you could use a page template to write your own queries, showing search results on a different URL (you would have to modify all search forms to go here instead).

    When you visit your websites home URL and add ?s= to the URL, WordPress knows to serve search.php and run a "main query" (using WP_Query) behind the scenes. The main query is what you are looping through when you call while( have_posts() ) etc.

    Writing your own queries to show search results may make your code less compatible with plugins that modify the main query to show more meaningful search results. It depends on how they do the logic of whether or not to modify a specific query. For example, they may check that the query is a main query and that you are on the search.php page. When you write your own queries using WP_Query or get_posts(), it's not a main query anymore.

    WP_Query (or get_posts() which calls WP_Query) should have an argument where you can specify the search term(s) and it may take care of parsing out all the different words and turning it into (somewhat) useful SQL. You should read the docs on WP_Query for more info.

    Sorry this is not a full answer but perhaps it will lead you in the right direction.