Woocommerce Product Search with Taxonomy - php

Hi have a search form that is allows the user to input a keyword then select a taxonomy via dropdown list. This is my form:
<form name="myCity" id="myCity" action="http://mywebsite.com/" method="post">
<div class="search-area">
<div class="container">
<div class="row-fluid">
<div class="span4">
<label><i class="icon-search"></i></label>
<div class="search-area-division search-area-division-input">
<input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder="I am searching for..."/>
</div>
</div>
<div class="span3">
<label><i class="icon-map-marker"></i></label>
<?php
$args = array('taxonomy' => 'pa_city');
wp_dropdown_categories( $args );
?>
</div>
</div>
<noscript><input type="hidden" onclick="WriteCookie()" class="btn btn-block btn-white search-btn" value="<?php echo esc_attr__( 'Search' ); ?>"/></noscript>
<input type="hidden" name="post_type" value="product" />
</div>
</div>
If I search mini-golf in Bullhead City,
it returns the URL:
http://mywebsite.com/?s=mini-golf&cat=14&post_type=product
While it returns products with the tag mini-golf, it returns all products regardless of city that match mini-golf. I have tried many ways to filter the results and am just spinning my wheels at this point.
The taxonomy I am using is pa_city. Even if the url is
http://mywebsite.com/?s=mini-golf&pa_city=bullhead-city&post_type=product
it does the same thing.
No matter which way I write this, it will NOT exclude the other cities in the search. Should I try a NOTIN? I can't figure out why it brings all products regardless of city...

I needed to filter the query further in my functions.php using pre_get_posts
Whew, that was a frustrating one.
function my_location( $q ){
if (!$q->is_main_query() )
return;
if ($q->is_search()) {
$city = isset( $_COOKIE['city'] ) ? $_COOKIE['city'] : 'not set';
$q->set( 'tax_query', array(array( 'taxonomy' => 'pa_city', 'field' => 'slug', 'terms' => array( $city ), 'operator' => 'IN' )));
return;
}
if ($q->is_archive() ){
if ( ! is_admin() ) {
if (empty($_COOKIE['city'] )) {
echo "<script>window.location.href = 'http://mywebsite.com/select-city/';</script>";
exit();
}
$city = isset( $_COOKIE['city'] ) ? $_COOKIE['city'] : 'not set';
$q->set( 'tax_query', array(array( 'taxonomy' => 'pa_city', 'field' => 'slug', 'terms' => array( $city ), 'operator' => 'IN' )));
}}
}
add_action( 'pre_get_posts', 'my_location' );

Related

Does not work meta_value_num wordpress, how to fix?

I'm trying to implement a product filter myself, but sorting by price refuses to work.
code:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="post-date-filter">
<?php
if( $terms = get_terms( 'product_cat', 'orderby=name' ) ) :
foreach ( $terms as $term ) :
echo '<label><input type="checkbox" name="categoryfilter[]" value="' . $term->term_id . '">' . $term->name . '</label>';
endforeach;
endif;
?>
<label>
<input type="radio" name="orderby" value="ASC" /> Price: Ascending
</label>
<label>
<input type="radio" name="orderby" value="DESC" /> Price: Descending
</label>
<button>Submit</button>
<input type="hidden" name="action" value="customfilter">
</form>
in function.php:
function posts_filters(){
if( isset( $_POST['categoryfilter'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $_POST['categoryfilter'],
'operator' => 'in'
)
);
if( isset( $_POST['orderby'] ) )
$args['meta_query'][] = array(
'key' => '_price',
'orderby' => 'meta_value_num',
'order' => $_POST['orderby']
);
everything works except sorting by price, I don't understand what the reason is...

Post filtering in wordpress returns all posts

I have this function to filter posts by fields and taxonomies. The problem is that when I use the taxonomy filter it doesn't work and it returns all the posts without filtering.
I didn't include js files because ajax is working well.
Here's the PHP in functions.php:
function post_filter()
{
$number = $_POST['number'];
$autor = $_POST['autor'];
$args = array(
'post_type' => 'publicaciones',
'orderby' => 'date',
'order' => 'ASC',
'meta_key' => 'numero',
'meta_value'=> $number
);
if( isset( $autor ) )
$args['tax_query'] = array(
array('taxonomy' => 'autors',
'field' => 'id',
'terms' => $autor)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
//Post content
endwhile;
wp_reset_postdata();
else :
echo 'No results.';
endif;
wp_die();
}
And this is the form:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" class="my-5" id="buscador_numero">
<div class="row">
<div class="col-3">
<?php
if( $terms = get_terms( array( 'taxonomy' => 'autors', 'orderby' => 'name' ) ) ) :
echo '<select name="autor"><option value="">Autor/a</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
?>
</div>
<div class="col-2">
<input type="number" class="w-100 p-2" name="number" placeholder="Número">
</div>
<div class="col-2">
<button id="btn_buscar"><span class="dashicons dashicons-search"></span></button>
</div>
</div>
<input type="hidden" name="action" value="post_filter">
</form>
Thanks in advance :)

'key' meta_query not working custom advanced search (WordPress)

Been trying for hours now and have almost got to breaking point. Tried so many different things but can't seem to get my custom search bar to query results by a pre-defined select price range. I am using Advanced Custom Fields to add the meta tag 'investmentprice' to my custom post type called 'investments'. I feel like it's to do with WordPress not picking up the correct 'key' in my meta_query, even though I have changed this numerous times now.
Here's the code for the config bar:
<div class="config_bar cf">
<form method="get" role="search" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="hidden" name="s" value="">
<input type="hidden" name="post_type" value="investments" />
<div class="col">
<?php
$taxonomy = 'type';
$args = array( 'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true,
);
$tax_terms = get_terms($taxonomy, $args);
?>
<span class="label_inner">Investment Type</span>
<select name="type" id="type" class="postform standard">
<option value="" selected="selected">All Investment Types </option>
<?php if($tax_terms): ?>
<?php foreach ($tax_terms as $tax_term): ?>
<?php $title = $tax_term->name;
?>
<option value="<?php echo $tax_term->slug; ?>"><?php echo $title; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div><!-- col -->
<div class="col">
<span class="label_inner"><?php _e('Select Country','opencloud');?></span>
<select class="postform standard country " name="country" id="country">
<option value=""><?php _e('All Countries','opencloud');?></option>
<?php
// Display only parents here .
$terms = get_terms( array(
// Put your taxonomy name here.
'taxonomy' => 'location',
'parent' => 0,
'hide_empty' => false
) );
foreach ($terms as $term){?>
<!-- We are going to send value for $_POST and data-makeId's TERM_ID for ajax request -->
<option value="<?php echo $term->slug;?>" data-countryId="<?php echo $term->term_id ?>"><?php echo $term->name;?></option>
<?php
wp_reset_query(); // if you're not in your main loop! otherwise you can skip this
} ?>
</select>
</div><!-- col -->
<script type="text/javascript">
$( document ).ready(function() {
$('#country').change(function(){
var $mainCat= $(this).find(':selected').attr('data-countryId');
if ($mainCat != '0' ){
// call ajax
$("#city").empty();
$.ajax
(
{
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=get_city_lists_ajax&main_catid=' + $mainCat,
beforeSend:function()
{
},
success:function(results)
{
$("#loading_bar").hide();
$("#city").removeAttr("disabled").trigger('change.select2');
$("#city").append(results).trigger('change.select2');
}
}
);
}
});
});
</script>
<div class="col">
<span class="label_inner"><?php _e('Select City','opencloud');?></span>
<select class="postform standard city " name="city" id="city" disabled>
<option value="<?php echo $term->slug;?>"><?php _e('All Cities','opencloud');?></option>
</select>
</div><!-- col -->
<div class="col">
<span class="label_inner">Select Price</span>
<select class="postform standard price" name="price" id="price">
<option value="">All Prices</option>
<option value="500-1000">£500-£1000</option>
<option value="1000-1500">£1000-£1500</option>
<option value="1500-2000">£1500-£2000</option>
<option value="2000-5000">£1500-£2000</option>
<option value="5000-10000">£5000-£10,000</option>
</select>
</div><!-- col -->
<div class="col">
<button class="search_submit" type="submit">Search</button>
</div><!-- col -->
</form>
And here's my advanced search query function:
function advanced_search_query( $query ) {
if ( isset( $_REQUEST['search'] ) && $_REQUEST['search'] == 'advanced' && !is_admin() && $query->is_search && $query->is_main_query() ) {
// limit query for custom post type
$query->set( 'post_type', 'investments' );
// Get query strings from URL and store the min a variable
$_type = $_GET['type'] != '' ? $_GET['type'] : '';
$_country = $_GET['country'] != '' ? $_GET['country'] : '';
$_city = $_GET['city'] != '' ? $_GET['city'] : '';
$_price = $_GET['price'] != '' ? $_GET['price'] : '';
if( $_price != '' ) {
$metaquery = array(
array(
'key' => 'investmentprice',
'terms' => $_price,
'compare' => 'BETWEEN'
)
);
$query->set( 'meta_query', $metaquery );
}
// if type is not empty limit the taxonomy to the specified
if( $_type != '' ) {
$taxquery = array(
array(
'taxonomy' => 'type',
'field' => 'slug',
'terms' => $_type,
'operator'=> 'IN'
)
);
$query->set( 'tax_query', $taxquery );
}
// if country is not empty limit the taxonomy to the specified
if( $_country != '' ) {
$taxquery = array(
array(
'taxonomy' => 'country',
'field' => 'slug',
'terms' => $_country,
'operator'=> 'IN'
)
);
$query->set( 'tax_query', $taxquery );
}
// if city is not empty limit the taxonomy to the specified
if( $_city != '' ) {
$taxquery = array(
array(
'taxonomy' => 'city',
'field' => 'slug',
'terms' => $_city,
'operator'=> 'IN'
)
);
$query->set( 'tax_query', $taxquery );
}
return; // always return
}
}
Also, here's a screenshot of the Advanced Custom Field:
Unless there are any other issues, this should be a small fix. You are using the array key 'terms' instead of 'value' in your meta query. According to the WordPress Codex, a nested array of args for a meta query should use value, like this:
$metaquery = array(
array(
'key' => 'investmentprice',
'value' => $_price,
'compare' => 'BETWEEN'
)
);
$query->set( 'meta_query', $metaquery );
Hope that helps..

How do I POST values to a taxonomy archive using pre_get_posts()

I have a form (a search form) on a single page. The code is below.
I wish to post the values of the form fields over to a pre_get_posts() function and then use the "properties" post type archive template (archive_properties.php) to then show the results.
I have posted my pre_get_post function below the form and I was hoping that would be sufficient.
Im getting the following error:
Warning: Invalid argument supplied for foreach() in /var/www/address/wp-admin/includes/plugin.php on line 1432
Ive got
function knoppys_search_form() { ?>
<form action="" id="propertySearch" name="propertySearch" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post" enctype="multipart/form-data" >
<div class="form-unit">
<select name="type">
<option value="">All</option>
<option value="Apartment">Apartments</option>
<option value="Villa">Villa</option>
</select>
</div>
<div class="form-unit">
<select name="location">
<?php $termsArgs = array( 'taxonomy' => 'locations' );
$terms = get_terms($termsArgs);
?>
<option value="">Location</option>
<?php foreach ($terms as $term) { ?>
<option value="<?php echo $term->term_id; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
</div>
<div class="form-unit">
<input type="number" min="0" name="bedfrom" placeholder="Bed From">
</div>
<div class="form-unit">
<input type="number" min="0" name="bedto" placeholder="Bed To">
</div>
<input type="hidden" name="action" value="">
<button class="btn btn-primary" type="submit"><i class="fa fa-search"></i> Submit</button>
function knoppys_pre_get_filter() {
if (!is_admin() && is_archive('properties')) {
$location = $_POST['location'];
$type = $_POST['type'];
$bedfrom = $_POST['bedfrom'];
$bedto = $_POST['bedto'];
//Get the correct location
$tax_query = array(
'taxonomy' => 'locations',
'field' => 'id',
'terms' => $location
);
$query->set( 'tax_query', $tax_query );
//Get the correct type
$meta_query = array(
'relation' => 'AND',
array(
'meta_key' => 'type_name',
'value' => $type
),
array(
'meta_key' => 'number_of_beds',
'value' => array($bedfrom, $bedto),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
);
$query->set( 'meta_query', $meta_query);
}
}
add_action('pre_get_posts', 'knoppys_pre_get_filter');

wp_insert_post custom taxonomy input to multiple posts

I have a front end form which will create two individual posts from the one form. My issue is when setting the custom taxonomy for each post, it will only input the first selection and not the full array of selections.
If I remove the [$key] from $services = $taxinput["job_listing_category"][$key];, it will then add all of the taxonomy selections from both inputs to both of the two posts.
I cant work out why I either have just a single taxonomy selection only applied to the correct individual post, or I have all taxonomy selections from both inputs added to both posts.
if($_POST){
foreach($_POST['class_name_1'] as $key =>$makepost)
{
if(strlen($makepost)>3){
$post_id = -1;
$taxinput = $_POST["tax_input"];
$services = $taxinput["job_listing_category"][$key];
$class_name_1 = $_POST['class_name_1'][$key];
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => '',
'post_title' => '',
'post_status' => 'pending',
'post_type' => 'job_listing',
'post_content' => ''
)
);
wp_set_post_terms( $post_id, $services, 'job_listing_category', true);
wp_add_post_meta( $post_id, 'class_name_1', $class_name_1);
}
}
}
Here is my frontend input form:
<form action="" method="post" id="submit-class" class="job-manager-form" enctype="multipart/form-data">
<div class="class-name-edit">
<label for="class_name">Class Name:</label>
<div class="field ">
<?php
get_job_manager_template( 'form-fields/text-field.php',
array(
'key' => 'class_name_1[]',
'field' => $all_fields['class_name_1']
)
);
?>
</div>
</div>
<div class="service-category classes">
<label for="job_category">Class categories:</label>
</div>
<?php
get_job_manager_template( 'form-fields/term-checklist-field.php',
array(
'key' => 'job_category[]',
'field' => $all_fields['job_category']
)
);
?>
</div>
</div>
<div class="class-name-edit">
<label for="class_name">Class Name:</label>
<div class="field ">
<?php
get_job_manager_template( 'form-fields/text-field.php',
array(
'key' => 'class_name_1[]',
'field' => $all_fields['class_name_1']
)
);
?>
</div>
</div>
<div class="service-category classes">
<label for="job_category">Class categories:</label>
</div>
<?php
get_job_manager_template( 'form-fields/term-checklist-field.php',
array(
'key' => 'job_category[]',
'field' => $all_fields['job_category']
)
);
?>
</div>
</div>
<div class="whitebox submitform">
<input type="submit" name="submit_job" class="button" value="Submit for Admin Approval" />
</div>
</form>

Categories