Home > Enterprise >  WordPress/WooCommerce filter by custom date field and exclude products older than current date
WordPress/WooCommerce filter by custom date field and exclude products older than current date

Time:04-09

I want to display a list of products sorted by date and I want to exclude products, where the date from my custom date field is older compared to the todays date. I got the query so far and it's already filtering but I don't know how to exclude products where the date is older than the current date. Can somebody assist me?

$today = date("Y/m/j");
        $products = wc_get_products(array(
            'limit' => 4,
        'meta_key' => 'event_date',
        'orderby' => 'meta_value',
        'order' => 'ASC',
            'meta_query' => array(
                array(
                   'key' => 'event_date',
                //    'meta-value' => $value,
                   'value' => $today,
                   'compare' => '>=',
                   'type' => 'CHAR'
               )
        )
        ));

From what I got so far I have one line with meta-value => $value, what is this actually?

CodePudding user response:

function handle_custom_query_var( $query, $query_vars ) {
    if ( ! empty( $query_vars['customvar'] ) ) {
        $query['meta_query'][] = array(
            'key' => 'event_date',
            'value' => esc_attr( $query_vars['customvar'] ),
            'compare' => '>='
        );
    }

    return $query;
}
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 );

$products = wc_get_products( array( 'customvar' => date('Y-m-d H:i:s') ) );

See the complete code reference here

  • Related