Filter products based on a custom field in WooCommerce

Viewed 1811

I have a question regarding custom fields in WooCommerce: Is there any way to display products based on custom field meta key and value?

I created a product custom field for delivery, the meta key is custom_text_field_delivery, and values are, 24h, 5days and 7days.

Then I tried to get them by URL like: localhost/shop/?custom_text_field_delivery=24h, but it didn't worked.

Is there any way to display them or I should create single page for each option?

1 Answers

You can use the following, to filter products based on a custom field in a query string with:

add_filter( 'woocommerce_product_query_meta_query', 'filter_products_with_custom_field', 10, 2 );
function filter_products_with_custom_field( $meta_query, $query ) {
    $meta_key = 'custom_text_field_delivery'; // <= Here define the meta key
    
    if ( ! is_admin() && isset($_GET[$meta_key]) && ! empty($_GET[$meta_key]) ) {
        $meta_query[] = array(
           'key'   => $meta_key,
           'value' => esc_attr($_GET[$meta_key]),
        );
    }
    return $meta_query;
}

You will be able to filter products by URL like: localhost/shop/?custom_text_field_delivery=24h.

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related