The variable $category is received as “summersummer” or “all-seasonall-season”.
Is there any way for me to split this? I am trying to pass it on as a term.
Here is my code.
function advanced_search_query($query) {
if($query->is_search()) {
// category terms search.
$category = $_GET['category'];
$string_array = explode(" ",$category);
print_r($string_array);
$taxonomy = 'product_cat';
if (isset($category) && !empty($category)) {
$args = array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $category
)
);
$query->set('tax_query', $args);
}
return $query;
} } add_action('pre_get_posts', 'advanced_search_query', 1000);
The print_r gives me Array ( [0] => all-season ) Array ( [0] => all-season )
EDIT 1 (The code sending the value for $category):
<form role="search" method="get" class="woocommerce-product-search" action="<?php print_r( $query ); ?><?php echo esc_url( home_url( '/' ) ); ?>">
<label class="screen-reader-text" for="s"><?php _e( 'Search for:', 'woocommerce' ); ?></label>
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search Products…', 'placeholder', 'woocommerce' ); ?>" value="<?php echo get_search_query(); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label', 'woocommerce' ); ?>" />
<select name="category">
<option value="winter">Winter</option>
<option value="all-season">All Season</option>
<option value="run-flat">Run Flats</option>
<option value="summer">Summer</option>
</select>
<input type="submit" value="<?php echo esc_attr_x( 'Search', 'submit button', 'woocommerce' ); ?>" />
<input type="hidden" name="post_type" value="product" />
The issue you have is with the code you’ve written being run multiple times rather than a variable duplicating a string.
You need to do more checking inside your
pre_get_posts
callback before modifying the query / outputting the string for testing.Change this:
To:
I’d also suggest splitting this into two conditionals but I didn’t want to overcomplicate things. We’re checking we’re not in the admin first. It’s not relevant to your question but an important check when using
pre_get_posts
. Then we’re checking that we’re operating on the main query on the page.pre_get_posts
will fire multiple times on a page load so we have to be sure we’re only modifying the main posts loop.