Wordpress - Custom Search on Custom Page while preserving the standard search function.
Hi all,
I would like to create a custom search on a custom page on top of main search function. The additional one is supposed to be focused only on products.
search-product.php
$product_type = $_GET['post_type'];
$args = array(
'post_type' => $product_type,
'posts_per_page' => -1
);
$the_query = new WP_Query($args);
/* Start the Loop */
while ($the_query -> have_posts() ) : $the_query -> the_post(); ?>
<h5><?php the_title(); ?></h5>
<?php endwhile; wp_reset_query(); ?>
The form:
<form role="search" method="get" class="search-form" action="<?php echo esc_url(home_url('/search-products/')); ?>">
<div class="row align-items-center">
<input type="hidden" name="post_type" value="product">
<input type="text" name="productname" value="" autocomplete="off" placeholder="Product Name..." class="searchForm form-control">
<button type="submit" class="btn btn-primary">Szukaj</button>
</div>
</form>
When I define the post type within the php file, it displays the query as expected. But I want to be able to modify the query on this page with URL instructions, however if I do something like this: http://localhost/wordpress/search-product/?post_type=product
WP returns the "page not found" page, with a different template. I believe it's the default "search" template.
Now... I know that I can/should modify the search.php file to make the whole thing work, BUT, I don't want to modify the main search.php (main query ? ).
I want to preseve the main search functionality, and have another custom one on top of it.
I have also utilized the template_include function as filter - however this returns a page, that visually is aligned with what I expect, however the head title is still "page not found".
I also tried to use the "pre_get_posts" hook, but also with no success.
I have spend lots of hours on this page to find the solutions, but all the answers include modifing the standard search.php file, but as mentioned, I do not want to modify the main search template.
Thanks!
form
there, remove the<input type="hidden" name="post_type" value="product">
, and in search-product.php, change$product_type = $_GET['post_type'];
to$product_type = 'product';
. Because I think the field'sname
(i.e.post_type
) conflicts with the standardWP_Query
request. So either you change thename
(to something likecust_post_type
) or do like I've suggested, which is hard-code the value in search-product.php. Hope that helps.