简体   繁体   中英

Do not show expiration date information on Wordpress posts

I am using the code below to report the time it takes for a post expires in my Wordpress site, the value of expiration I define in a Custom Field (expiration).

From this code, as I do I keep a post that will expire in about four hours, does not display the information in this way: "Expires in 0 days , 4 hours and 49 minutes."

I do not want the "0 days" is displayed, only the remaining hours. In the case of the post expires the next day, so good, could be displayed normally "Expires in 1 day, 4 hours and 49 minutes."

In addition, there are posts that I do not define expiration, and they all appear the following information: "Expires in 0 days , 2 hours and 0 minutes." How do I display information like "Undetermined Expiration" for these posts?

           <?php 
                $date_now    = date( 'm/d/Y H:i:s', current_time( 'timestamp', 0 ) );
                $date_expire = get_field('expiration');

                $now     = new DateTime($date_now);
                $expires = new DateTime($date_expire);

                $diff = $expires->diff($now)->format("%a days, %h hours and %i minutes");

                if ($now < $expires) {
                    echo "Expires em $diff", PHP_EOL;
                } 
                else if ($now >= $expires) {
                    echo "Expired!", PHP_EOL;
                }
                else {
                    echo "", PHP_EOL;
                }
            ?>

Use this code:

$now     = new DateTime( $date_now );
$expires = new DateTime( $date_expire );

$diff = $expires->diff($now);

if( $diff->days ) $diff = $diff->format( "%a days, %h hours and %i minutes" );
else              $diff = $diff->format( "%h hours and %i minutes" );

->days is the only absolute DateTime property.

If you want display only minutes when the difference is lower than 1 hour, you can change above code in this way:

if( $diff->days  ) $diff = $diff->format( "%a days, %h hours and %i minutes" );
elseif( $diff->h ) $diff = $diff->format( "%h hours and %i minutes" );
else               $diff = $diff->format( "%i minutes" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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