简体   繁体   English

显示来自 2 个自定义日期选择器字段的日期范围

[英]Display date range from 2 custom date-picker fields

I've created two custom datepicker fields with ACF (beginning_date and completion_date) and need to output/display these as a date range.我已经使用 ACF(beginning_date 和 completion_date)创建了两个自定义日期选择器字段,并且需要将它们输出/显示为日期范围。

For example, if beginning_date Year and completion_date Year are equal, I need to output beginning_date day/month - completion day/month/year.例如,如果 beginning_date Year 和 completion_date Year 相等,我需要 output beginning_date day/month - completion day/month/year。

The display and return format these fields use is: l, F j, Y这些字段使用的显示和返回格式是:l, F j, Y

I've searched everywhere: And tried to implement this: Create display date range from two dates in ACF in Wordpress我到处搜索:并尝试实现这一点: Create display date range from two dates in ACF in Wordpress

I also attempted to convert the fields to datetime objects but comparing these as dates seems to be the wrong way.我还尝试将字段转换为日期时间对象,但将它们作为日期进行比较似乎是错误的方式。 I do not know where else I'm failing at.., I'm beginning again as nothing has worked so far, so I have no code to publish here because I ended up with a Frankenstein code snippet which I deleted and then came here for desperate help!我不知道我还有什么地方失败了......,我重新开始,因为到目前为止没有任何效果,所以我没有代码可以在这里发布,因为我最终得到了一个 Frankenstein 代码片段,我删除了它然后来到这里绝望的帮助!

in your functions.php在你的函数中.php

 function date_compare($id){
    
    $start_date = get_field('beginning_date', $id);
    $end_date = get_field('completion_date', $id);
    
    $start_year = wp_date("Y", strtotime( $start_date ) );
    $end_year = wp_date("Y", strtotime( $start_date ) );
    
    $start_month = wp_date("n", strtotime( $start_date ) );
    $end_month = wp_date("n", strtotime( $start_date ) );
    
    $date_output = '';
    
    $start_date_format = "l, F j, Y";
    
    if( $start_date && $end_date ){
        
        if( $start_year == $end_year && $start_month == $end_month ){
            $start_date_format = "l j";
        }
        elseif( $start_year == $end_year){
            $start_date_format = "l, F j";
        }

    }
    
    
    if( $start_date ){
        $date_output .= wp_date($start_date_format, strtotime( $start_date ) );
    }
    
    if( $end_date ){
        $date_output .= ' - ' . wp_date("l, F j, Y", strtotime( $end_date ) );
    }
    
    return $date_output;
}

and in your theme:在你的主题中:

echo date_compare($post->ID);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM