wordpress - 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() ) : ?>
有了这个,我得到一个类似的列表:
- 05.03.2002 - A 人
- 11.03.1998 - B 人
- 24.03.1995 - C 人
- 03.03.1970 - 人 D
我的目标是一个列表,按天排列,而不是按年份排列,例如:
- 03.03.1970 - 人 D
- 05.03.2002 - A 人
- 11.03.1998 - B 人
- 24.03.1995 - C 人
对我有什么提示吗?谢谢
解决方案
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);
推荐阅读
- javascript - React Native - 在 React Native 中真的需要 Redux-Persist 吗?
- r - 如何在 R 编程中解决这个问题(因为未指定“lib”)?
- java - 如果第一个和最后一个字符是元音,则打印 isvowel 字符串?
- python - 领英自动化
- r - 将折线图更改为堆叠折线图 ggplot
- swift - 在 swift 5 中,图像文字数组得到“表达式类型不明确,没有更多上下文”
- python - 我想从本地分支运行我的 Django 项目。有没有办法做到这一点?
- java - 主启动器 =true 在 Xamarin android 中不起作用(system.typeloadexception)
- python - Flask 无法从 html 表单中选择数据
- azure - 从 Azure SQL 导出数据后如何添加主键和外键约束