最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Searching for a specific month in a metadata saved as Timestamp (Wp_Query)

programmeradmin0浏览0评论

I need to keep the payment dates for a post type I created called "Payments." For this, I created a meta key called "expected_payment_date". I save the expected payment dates as timestamp. For example, I keep the date 2020-05-15 as 1589490000.

I want to list all payments that should be made in a given month using Wp_Query. I try the method below for this, but I got no results. Do you know how I can do this?

$month = '2020-05';
$args = array(
    'post_type'       => array( 'payments' ),
    'posts_per_page'  => -1,
    'post_status'     => array( 'publish' ),
    'meta_query '     => array(
        'key' => 'expected_payment_date',
        'value' => $month,
        'compare' => 'LIKE'
    )
);

Note: I tried other comparisons like = EXIST in the Compare section.

I need to keep the payment dates for a post type I created called "Payments." For this, I created a meta key called "expected_payment_date". I save the expected payment dates as timestamp. For example, I keep the date 2020-05-15 as 1589490000.

I want to list all payments that should be made in a given month using Wp_Query. I try the method below for this, but I got no results. Do you know how I can do this?

$month = '2020-05';
$args = array(
    'post_type'       => array( 'payments' ),
    'posts_per_page'  => -1,
    'post_status'     => array( 'publish' ),
    'meta_query '     => array(
        'key' => 'expected_payment_date',
        'value' => $month,
        'compare' => 'LIKE'
    )
);

Note: I tried other comparisons like = EXIST in the Compare section.

Share Improve this question asked May 19, 2020 at 7:21 FarukFaruk 2510 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I found the solution after a long search. Thank you very much to Misha Rudrastyh who gave me a great idea in my solution. You can check out the great guide that he prepared for meta_query.

Here is the solution:

First, get the first and last day of the month as described here (thanks for Francois Deschenes).

$month = '2020-05';

// First day of the month.
$first_day = strtotime( date('Y-m-01', strtotime($month)) );
// Last day of the month.
$last_day = strtotime( date('Y-m-t', strtotime($month)) );

I use it as a timestamp because I keep the expected payment dates in this way. For more details, I suggest you check Misha's guide.

Once you have the dates correctly fetched, all you have to do is prepare the wp_query arguments.

$args = array(
    'post_type'       => array( 'payments' ),
    'posts_per_page'  => -1,
    'post_status'     => array( 'publish' ),
    'meta_query '     => array(
        'key' => '_eo_payment_expected_date',
        'value' => array( $first_day, $last_day ),
        'type' => 'numeric',
        'compare' => 'BETWEEN'
    )
);

That is all.

发布评论

评论列表(0)

  1. 暂无评论