简体   繁体   中英

Woocommerce - Disable or Hide product based on custom field value (ACF)

I am trying to hide products on my site based on logical conditions with their custom field values (provided by Advanced Custom Fields Plugin - ACF ).

I have referenced a number of articles about excluding products based on certain criteria, testing with the pre_get_posts , woocommerce_product_query_tax_query and woocommerce_product_query hooks. All of which won't let me access the ACF values so that I can filter the $tax_query terms.

My end goal here is to hide specific products that have a date set in its custom field and that date is in the past. I access the custom field using the get_field('event_date'); function.

I am looking for someone to help me develop this code to filter products based on their Advanced Custom Field value.

There is a lot I have tried so far, and I've looked at the var_dumps to see what I can use, but the truth is I'm still at square one. Here is my laughable progress:

add_action('woocommerce_product_query', 'filter_past_events');
function filter_past_events($q)
{
    // Return is event_date variable is not set
    if (get_field('event_date')) {
        $eventDate = new DateTime(get_field('event_date')); // Format ISO-8601 (YYYY-MM-DD)
        $now = new DateTime();
        if ($eventDate < $now) {
            // event is in the past
        }
    }
}

So far, I have referenced:

Exclude products from a particular category on the shop page

filter-woocommerce-products-based-on-custom-product-attribute-value

function custom_pre_get_posts_query($q) {
    $meta_query   = $q->get('meta_query');
    $meta_query[] = array(
        'key'     => 'key',
        'value'   => 'value',
        'compare' => '!='
    );

    $q->set('meta_query', $meta_query);
}

add_action('woocommerce_product_query', 'custom_pre_get_posts_query');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM