John Davidson

php - WooCommerce: Custom search form that shows product attributes and queries them

0 comments
Message:


I want to add a custom search form incl. an option to choose certain product attributes. The goal is that users can input a text and choose a product attribute value and results are only shown from a certain product category.


I know that I can utilize the type parameter of input to build a custom URL. How can I include the terms of a attributes as well?


By using this answer (https://wordpress.stackexchange.com/questions/184166/create-product-category-and-keyword-search-form-in-woocommerce) my code looks like this so far:


function custom_search( $form ) {

$terms = get_terms('pa_attributes');

$form = '<form role="search" method="get" id="searchform" action="' . esc_url( home_url( '/' ) ) . '">
<div>
<label class="screen-reader-text" for="s">' . __( 'Search for:', 'woocommerce' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" placeholder="' . __( 'Search within a category', 'woocommerce' ) . '" />
<input type="hidden" name="post_type" value="product">
<input type="hidden" name="taxonomy" value="product_cat">

<!-- here: my_product_category is chosen -->
<input type="hidden" name="term" value="my_product_category">

<!-- HOW TO INCLUDE $terms ? -->


<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search', 'woocommerce' ) .'" />
<input type="hidden" name="post_type" value="product" />
</div>
</form>';

return $form;
}


My Answer:
To include the terms of product attributes in your custom search form, you can create a select dropdown input field for each attribute and populate it with the terms of that attribute. Here's how you can modify your code to include the terms of product attributes:

php
function custom_search( $form ) {
$terms = get_terms('pa_attributes');

$form = '';

return $form;
}


In this code snippet, I added two select dropdown input fields for product attributes. You can add more select dropdowns as needed for additional attributes. Make sure to replace `attribute1` and `attribute2` with the actual attribute names. Also, adjust the loop to fetch the terms of each attribute if needed.

This way, users can select a product attribute value along with their search query, and the form will submit the selected attribute values along with the search query to filter the search results accordingly.

Rate this post

3 of 5 based on 9717 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us