How to filter Woocommerce Products with a Custom Field, WC Vendors Compatible
September 24, 2016 Wordpress Coding
I was creating a multi-vendor site for my client & needed to filter out products with a custom field, locality. I looked around but there was no plugin for this process.
So, with a little bit of coding I sorted the best way to filter Woocommerce products with a custom field.
Current Setup:
Wordpress 4.6
Woocommerce
WC Vendors
Advanced Custom Field (Free Version)
We will be using Advanced Custom Field (Free Version) to create a Locality Field (Multi-Select).
This is how the Add/Edit Product looks after adding custom field via ACF. You can use any other plugin or custom code for this purpose.
Now we need to write some code so that we can filter our products according to this custom field. Just use the code given below and paste it in your theme’s function.php file.
/**
* Locality filter.
*/
add_action( 'pre_get_posts', 'pre_get_posts_locality_filter' );
function pre_get_posts_locality_filter( $query ) {
if( is_admin() ){
return;
}
$meta_query = $query->get( 'meta_query' );
if( isset( $_GET['locality_delivery'] ) ){
$meta_query[] = array(
'key'=> 'locality-delivery',
'value'=> $_GET['locality_delivery'],
'compare'=> 'LIKE'
);
$query->set( 'meta_query', $meta_query );
}
return;
}
Just use this code & you can now filter products in woocommerce with a custom field.
How will the above code work?
Once you paste the code above, you can filter the products using:
www.example.com/shop/?locality_delivery=localityname
Feel free to ask any questions & comment if this helped you.
Leave a Comment
You must be logged in to post a comment.
Specify Facebook App ID and Secret in the Super Socializer > Social Login section in the admin panel for Facebook Login to work
Specify Google Client ID and Secret in the Super Socializer > Social Login section in the admin panel for Google and Youtube Login to work