John Davidson

php - WordPress/WooCommerce filter by custom date field and exclude products older than current date

0 comments
Message:


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?



My Answer:
'Y-m-d');
$args = array(
'post_type' => 'product',
'meta_key' => 'custom_date_field',
'orderby' => 'meta_value',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'custom_date_field',
'value' => $today,
'compare' => '>=',
'type' => 'DATE'
)
)
);

$products = new WP_Query($args);

if ($products->have_posts()) {
while ($products->have_posts()) {
$products->the_post();
// Display your product here
}
} else {
// No products found
}

In this code snippet, we are querying products with a custom date field and sorting them by the custom date field in descending order. We are also using a meta query to filter out products where the custom date field is greater than or equal to the current date.

This should help you achieve your goal of displaying a list of products sorted by date and excluding products where the date is older than the current date.

Rate this post

3 of 5 based on 8424 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us