i have been trying to use wordpress wp_query method, but my case is specific.
I need to select all product of the current month so here is my code
$args = array(
'numberposts' => -1,
'post_type' => 'product',
'meta_query' => array(
'Relation' => 'AND',
array(
'key' => 'wpcf-product_status',
'value' => 'valid',
'compare' => '='
),
array(
'key' => 'wpcf-product-start_date',
'compare' => '=',
'date_query' => array(
array(
'month' => date('m'),
'compare' => '=',
),
),
),
),
);
// get results
$the_query = new WP_Query( $args );
I can not get the exact result.
how is it possible to test only the date MONTH like it is done is SQL (WHERE MONTH(wpcf-product-start_date) = MONTH(NOW())
)
any idea please?
Here are few additional options:
If you want to filter a given month in a given year, you can just calculate the timestamp period for that month and use the corresponding compare operators of the meta query to filter it.
You might want to consider changing the format of the
wpcf-product-start_date
custom field values, toY-m-d
,Y-m
orm
, depending of your needs.You could use the
{added,updated,deleted}_post_meta
hooks (see for example this fine answer) to automatically save a new custom field, containing the month number calculated from thewpcf-product-start_date
timestamp. For example:Then you can use
wpcf-product-start-month
in your meta-query.Notice that I used
wpcf-product-start-date
here. Somehow this didn’t triggered for the custom field with the meta-keywpcf-product-start_date
. But let me know if you have problems with this.If you are adventurous you can play with the
posts_where
filter:where
Notice that this assumes that the
replace_me
value is in the second meta query array item.The table names can change if you reorder the array items (e.g.
wp_postmeta, mt1, ...
). It’s possible to find thecorrect table name automatically, but that’s beyond the scope of this answer.
Hope this help.
Try this. And be sure that ‘wpcf-product-start_date’ has got the same format of ‘date(‘m’)’ 🙂
OR…
You can get the month start and month end as a timestamp and use a ‘BETWEEN’ meta compare:
eg.
or…