Eri*_*ood 2 php wordpress datepicker unix-timestamp advanced-custom-fields
我有一个“即将发生的事件”页面和一个“过去的事件”页面。每个事件都有一个名为“event_date”的自定义字段。
我想创建一个循环来显示所有比今天更大的事件。我已经浏览了这些文章,但无法让它工作:http : //support.advancedcustomfields.com/forums/topic/how-do-i-filter-and-sort-event-posts-with -开始和结束日期/
https://wordpress.org/support/topic/plugin-advanced-custom-fields-sorting-by-date-picker
根据我在上面三个链接中收集的内容,我会将其放在我的 functions.php 文件中:
// CREATE UNIX TIME STAMP FROM DATE PICKER
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'event_type' ) {
$event_date = get_post_meta($post_id, 'event_date', true);
if($event_date) {
$dateparts = explode('/', $event_date);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
Run Code Online (Sandbox Code Playgroud)
然后我会在我的页面模板中添加这样的内容:
<?php
$today = time();
$args = array(
'post_type' => 'event_type',
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'unixstartdate',
'compare' => '>=',
'value' => $today,
)
),
'meta_key' => 'event_date',
'orderby' => 'meta_value',
'order' => 'ASC',
);
$query = new WP_Query( $args );
$event_type = $query->posts;
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
Run Code Online (Sandbox Code Playgroud)
现在这没有任何结果。我的帖子类型叫“event_type”,关键是“event_date”。
关于我哪里出错的任何想法?
感谢svsdnb,我在这里找到了解决方案。
https://wordpress.org/support/topic/query-date-array-to-display-future-events-only
不必在functions.php中转换时间戳,有一种方法可以专门使用您使用的ACF来做到这一点
current_time('Ymd')
Run Code Online (Sandbox Code Playgroud)
代替
$today = date ('Ymd')
Run Code Online (Sandbox Code Playgroud)
这是我最终得到的结果(它似乎有效,包括今天发生的事件):
<?php
$today = current_time('Ymd');
$args = array(
'post_type' => 'event_type',
'post_status' => 'publish',
'posts_per_page' => '0',
'meta_query' => array(
array(
'key' => 'event_date',
'compare' => '>=', // Upcoming Events - Greater than or equal to today
'value' => $today,
)
),
'meta_key' => 'event_date',
'orderby' => 'meta_value',
'order' => 'ASC',
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
?>
Run Code Online (Sandbox Code Playgroud)