首页 > 解决方案 > Wordpress 查询自定义日期字段按天排序

问题描述

我有一个名为“员工”的自定义帖子类型。在这个我有一个名为“生日”的自定义日期字段。

现在我需要查询当月所有生日的列表,按日期字段(生日)的日期排序,而不是按年份排序。

这是我到目前为止所拥有的:

<?php 
$current_month = date('m'); // get current month
$filter_month = $current_month; // show current month only
$args = array(
    'post_type'  => 'employees',
    'meta_key'=>'birthday',
    'posts_per_page' => -1,
    'orderby'=>'meta_value', 
    'order'=>'DESC', 
    'meta_query' => array(
        array(
            'key'     => 'birthday',
            'value'   => $current_month,
            'compare' => 'REGEXP',
            'value'   => '[0-9]{4}' . $filter_month . '[0-9]{2}',
        ),
    ),

);
$query = new WP_Query( $args );if ( $query ->have_posts() ) : ?>

有了这个,我得到一个类似的列表:

我的目标是一个列表,按天排列,而不是按年份排列,例如:

对我有什么提示吗?谢谢

标签: wordpressdateadvanced-custom-fields

解决方案


So here is a solution to your problem. I thought it might be easier to add additional meta fields, "birthday_month" and "birthday_day" - so if you add those on post_save hook, you dont' have to do any additional data entry.

add_action('save_post', 'he_add_birthday_details', 10, 1);
function he_add_birthday_details($postid){
// Check if birthday is set 
if (!empty(get_post_meta($postid, 'birthday', true))) {
    // if it is set - get it
    $birthday = get_post_meta($postid, 'birthday', true);
    // parse the date into components
    $month = date('m' , strtotime($birthday));
    $day = date('d', strtotime($birthday));
    // Save new postmeta fields
    update_post_meta($postid, 'birthday_month', $month);
    update_post_meta($postid, 'birthday_day', $day);
}

Then you can do your loop with the new fields.

 $current_month = date('m'); // get current month
 $filter_month = $current_month; // show current month only
 $args = array(
    'post_type'  => 'employees',
    'posts_per_page' => -1,
    'meta_query' => array(
     array(
        'key'     => 'birthday_month',
        'value'   => $current_month
     ),
     'date_clause' => array(
        'key' => 'birthday_day',
        'compare' => 'EXISTS'
        )   
    ),
    'orderby' => 'date_clause',
    'order' => 'ASC'
 );

$posts = new WP_Query($args);

推荐阅读