0

Нужно сделать вывод даты комментариев так:

  • если опубликован более 3 часов назад, то выводить дату как обычно
  • если опубликован менее 3 часов назад, то выводить "% часов/минут/секунд назад"

Подскажите, как реализовать.

Вот функции:

function get_comment_date( $d = '', $comment_ID = 0 ) {
    $comment = get_comment( $comment_ID );
    if ( '' == $d )
        $date = mysql2date(get_option('date_format'), $comment->comment_date);
    else
        $date = mysql2date($d, $comment->comment_date);
    /**
     * Filter the returned comment date.
     *
     * @since 1.5.0
     *
     * @param string|int $date    Formatted date string or Unix timestamp.
     * @param string     $d       The format of the date.
     * @param WP_Comment $comment The comment object.
     */
    return apply_filters( 'get_comment_date', $date, $d, $comment );
}

function get_comment_time($d = '', $gmt = false, $translate = true){
    $comment = get_comment();

    $comment_date = $gmt ? $comment->comment_date_gmt : $comment->comment_date;
    if ('' == $d)
        $date = mysql2date(get_option('time_format'), $comment_date, $translate);
    else
        $date = mysql2date($d, $comment_date, $translate);

    /**
     * Filter the returned comment time.
     *
     * @since 1.5.0
     *
     * @param string|int $date The comment time, formatted as a date string or Unix timestamp.
     * @param string $d Date format.
     * @param bool $gmt Whether the GMT date is in use.
     * @param bool $translate Whether the time is translated.
     * @param WP_Comment $comment The comment object.
     */
    return apply_filters('get_comment_time', $date, $d, $gmt, $translate, $comment);
}

Сейчас выводится так:

введите сюда описание изображения

5
  • mysql2date в каком формате дату отдает?
    – Invision
    22 янв 2016 в 17:28
  • @Invision d.m.Y 22 янв 2016 в 18:07
  • Ты забыл про H:i. Через функцию strtotime преобразуй в Unix timestamp, добавь условие если не прошло 3 часа от текущего time(), то выводить (return) в формате часов/минут/секунд назад. Как получить подобный формат гуляет много примеров. Пример biznesguide.ru/coding/193.html
    – Invision
    22 янв 2016 в 18:13
  • 1
    Лучше всего -- не делать это на сервере. Это не поддаётся кэшированию и с пребыванием страницы у клиента постепенно стареет.
    – user181100
    22 янв 2016 в 19:30
  • 1
    Если соберетесь делать на клиенте, обратите внимание на momentjs.com У нее есть и нужный функционал, и поддержка русского языка для дат.
    – VenZell
    22 янв 2016 в 21:47

1 ответ 1

1
function _ago($tm, $rcs = 0)
    {
        $cur_tm = time();
        $dif = $cur_tm - $tm;
        $pds = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade');
        $lngh = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
        for ($v = sizeof($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--) ;
        if ($v < 0) $v = 0;
        $_tm = $cur_tm - ($dif % $lngh[$v]);

        $no = floor($no);
        if ($no <> 1) $pds[$v] .= 's';
        $x = sprintf("%d %s ", $no, $pds[$v]);
        if (($rcs == 1) && ($v >= 1) && (($cur_tm - $_tm) > 0)) $x .= time_ago($_tm);
        return $x;
    }

UPD 1 : Carbon Установить Carbon через composer:

{
   "require": {
      "nesbot/carbon": "~1.18"
   }
}

В РНР:

<?php
use Carbon\Carbon;

echo Carbon::now()->diffForHumans($article->time); 

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.