Home Backend Development PHP Tutorial Optimize the time display of articles and comments in WordPress_php tips

Optimize the time display of articles and comments in WordPress_php tips

May 16, 2016 pm 07:59 PM
php wordpress time display

Many blogs like to use the comment posted "XXX minutes ago" and the article posted "XXX minutes ago" to display the time of the article comment. The improved time display method can not only intuitively tell readers that this article or comment was published How long has it been since now? It can enhance the sense of time in comment reply. I like it very much. Because there were too many things in my hands a while ago, and I was unable to access the Internet during the day during the working day, so the style and function of the theme were It took me a long time to write bit by bit, but recently it was my turn to comment, so I gradually modified my comment style and functions bit by bit based on the popular styles on the Internet.

So…..
Go…..
Jiaodao Sack... The comment date and the article date call functions differently. The following takes the comment date as an example. Please adjust the article date by yourself.

Principle of improved time display
It's very simple. It uses a built-in function of WordPress to process the difference between the current time and the time when the article or comment was published. It displays X minutes, X hours, and X days since now.
This function is human_time_diff ()

Usage:

 <&#63;php human_time_diff( $from, $to ) ;&#63;>

Copy after login

Description:
Determine the difference between two time stamps.
Returns the time difference between the two time variables $from and $to in human-readable format, such as "1 hour", "5 minutes", "two days".

It’s also easy to understand in English: from to to. (This sentence is very useless, haha.)

Prototype version improved

 //将你的评论时间显示的函数改成如下就可以了
<&#63;php echo human_time_diff( get_comment_time('U') , current_time('timestamp')) ;&#63;>

Copy after login

All dates are calculated with time differences. Isn’t it very violent?

How to implement the junior version
Simply add a judgment, if the comment time is not more than one day, it will display XX hours ago, if it is more than one day, it will display the original date.
Is this more humane? We can’t let readers count the days before 38 days on their fingers, right? Ha ha!
Code:

 <&#63;php 
//计算是否超过一天 注:86400是一天的总共的秒数 60秒X60分X24小时=86400秒
//如果觉得一天不够的话,请自行计算填上。
if (current_time('timestamp') - get_comment_time('U') < 86400 )
//一天之内显示的东西
{$cmt_time = human_time_diff( get_comment_time('U') , current_time('timestamp') ) . '-ago';}
//超过一天这么显示
else{$cmt_time = get_comment_date( 'Y/n/j' ).' - '.get_comment_time('','',false);};
 ;&#63;>


 //将你的评论时间显示的函数改成如下就可以了
<&#63;php echo $cmt_time ;&#63;>

Copy after login

Enhanced version
So can we enhance it a little more?
Why enhance?
Well, because I am a more serious person, I feel that the date displayed in Chinese is not good-looking, and it affects my layout. I like the date displayed in English, and the Chinese version of WordPress really has no dead ends (the Chinese version is really careful), if we directly If you use the human_time_diff function to output, the Chinese version of WordPress will display all the results in Chinese version XX hours and XX days ago, which is likely to affect our typesetting, and there is neither a hook nor a non-Chinese version reserved in the human_time_diff function. parameters, so if we want to display English, there are only two ways:

Directly modify the human_time_diff function to invalidate the Chinese version. This is too violent, and the Lun family doesn’t like it if you have to modify it again after upgrading.
Rewrite your own human_time_diff function to bypass Chinese translation.
Powerfully insert the following code into function.php:

 //原函数的 day hour min 都是小写的,
//我把这三个词的首写字母改成大写的,即Day Hour Min 就可以避开汉化了,你懂?
if ( ! function_exists( 'xz_time_diff' ) ) :
function xz_time_diff( $from, $to = '' ) {
 if ( empty($to) )
 $to = time();
 $diff = (int) abs($to - $from);
 if ($diff <= 3600) {
 $mins = round($diff / 60);
 if ($mins <= 1) {
  $mins = 1;
 }
 /* translators: min=minute */
 $since = sprintf(_n('%s Min', '%s Mins', $mins), $mins);
 } else if (($diff <= 86400) && ($diff > 3600)) {
 $hours = round($diff / 3600);
 if ($hours <= 1) {
  $hours = 1;
 }
 $since = sprintf(_n('%s Hour', '%s Hours', $hours), $hours);
 } elseif ($diff >= 86400) {
 $days = round($diff / 86400);
 if ($days <= 1) {
  $days = 1;
 }
 $since = sprintf(_n('%s Day', '%s Days', $days), $days);
 }
 return $since;
}endif;

Copy after login

The time judgment code is changed to the following:

 <&#63;php 
//只是把计算日期差异的函数名变了而已,其他同上。
if (current_time('timestamp') - get_comment_time('U') < 86400 )
{$cmt_time = xz_time_diff( get_comment_time('U') , current_time('timestamp') ) . '-ago';}
else{$cmt_time = get_comment_date( 'Y/n/j' ).' - '.get_comment_time('','',false);};
 ;&#63;>


 //将你的评论时间显示的函数改成如下就可以了
<&#63;php echo $cmt_time ;&#63;>

Copy after login

Show relative time of comments and articles

According to the above version, the following one should be considered an enhanced and improved version. Because to achieve the effect, you still need to add code to the theme, so it is not the final version yet, haha.
The function code is as follows:

Relative time function

if ( ! function_exists( 'xz_time' ) ) :
/**
 * 显示文章、评论相对时间的封装函数.
 *作者:XiangZi http://PangBu.com/
 * @param $type 类型字符串 'cmt'或'art',用于定义显示的是评论时间还是文章时间。
 * @param $ago_time 数字类型 用于定义显示相对时间的时间限制 默认为86400秒即一天。
 * @param $after 字符串型 显示在相对时间之后的文字,默认为 ' - ago'
 * @param $late 字符串型 超过时间限制后显示的项目,默认为 get_the_time('Y/n/j - H:i')或get_comment_time('Y/n/j - H:i')
 * @return 返回字符串(相对时间或绝对时间)
*/
function xz_time ( $type = 'art', $ago_time = 86400 ,$after = ' - ago' , $late = '' ) {
  if ( $type === 'cmt' ){
    $diff = (int) abs( get_comment_time('U') - current_time('timestamp'));
      if ( (!$late) || $late ==''){ $late = get_comment_time('Y/n/j - H:i');};
  }
  if ( $type === 'art' ){
    $diff = (int) abs( get_the_time('U') - current_time('timestamp'));
    if ( (!$late) || $late ==''){$late = get_the_time('Y/n/j - H:i');};
  }
  if ( $diff <= 3600 ) {
    $mins = round($diff / 60);
    if ($mins <= 1) {
      $mins = 1;
    }
    /* translators: min=minute */
    $since = sprintf(_n('%s Min', '%s Mins', $mins), $mins);
  } else if (($diff <= 86400) && ($diff > 3600)) {
    $hours = round($diff / 3600);
    if ($hours <= 1) {
      $hours = 1;
    }
    $since = sprintf(_n('%s Hour', '%s Hours', $hours), $hours);
  } elseif ($diff >= 86400) {
    $days = round($diff / 86400);
    if ($days <= 1) {
      $days = 1;
    }
    $since = sprintf(_n('%s Day', '%s Days', $days), $days);
  };
  $since .= $after ; 
  return $diff < $ago_time &#63; $since : $late ;
}endif;
Copy after login

How to use
Insert the above code into your theme’s function.php file
Then just call this function where you want to display the relative time.
The function must input at least one parameter, which is the $type type string ‘cmt’ (comment time) or ‘art’ (article time)
Example:

 //最简单的调用
echo xz_time('cmt');
//一天内的输出结果: 3 Hours-ago 
//一天后的输出结果: 2015/12/26 - 20:01
 
 
//调用时长为2天内的相对时间,之前时间显示默认时间
echo xz_time('cmt',172800);
//2天内的输出结果: 3 Hours-ago 
//2天后的输出结果: 2015/12/26 - 20:01
 
 
//调用时长为2天内的相对时间,相对时间之后显示 '之前的评论'
echo xz_time('cmt',172800,'之前的评论');
//2天内的输出结果: 3 Hours 之前的评论 
//2天后的输出结果: 2015/12/26 - 20:01
 
//调用时长为2天内的相对时间,之前时间显示为 年-月-日
echo xz_time('cmt',172800,'之前的评论',get_comment_time('Y-n-j'));
//2天内的输出结果: 3 Hours 之前的评论 
//2天后的输出结果: 2015/12/26

Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

How to cancel the editing date of wordpress How to cancel the editing date of wordpress Apr 20, 2025 am 10:54 AM

WordPress editing dates can be canceled in three ways: 1. Install the Enable Post Date Disable plug-in; 2. Add code in the functions.php file; 3. Manually edit the post_modified column in the wp_posts table.

How to change the head image of the wordpress theme How to change the head image of the wordpress theme Apr 20, 2025 am 10:00 AM

A step-by-step guide to replacing a header image of WordPress: Log in to the WordPress dashboard and navigate to Appearance &gt;Theme. Select the topic you want to edit and click Customize. Open the Theme Options panel and look for the Site Header or Header Image options. Click the Select Image button and upload a new head image. Crop the image and click Save and Crop. Click the Save and Publish button to update the changes.

How to write a header of a wordpress How to write a header of a wordpress Apr 20, 2025 pm 12:09 PM

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

What to do if there is an error in wordpress What to do if there is an error in wordpress Apr 20, 2025 am 11:57 AM

WordPress Error Resolution Guide: 500 Internal Server Error: Disable the plug-in or check the server error log. 404 Page not found: Check permalink and make sure the page link is correct. White Screen of Death: Increase the server PHP memory limit. Database connection error: Check the database server status and WordPress configuration. Other tips: enable debug mode, check error logs, and seek support. Prevent errors: regularly update WordPress, install only necessary plugins, regularly back up your website, and optimize website performance.

How to display wordpress comments How to display wordpress comments Apr 20, 2025 pm 12:06 PM

Enable comments in WordPress website: 1. Log in to the admin panel, go to "Settings" - "Discussions", and check "Allow comments"; 2. Select a location to display comments; 3. Customize comments; 4. Manage comments, approve, reject or delete; 5. Use &lt;?php comments_template(); ?&gt; tags to display comments; 6. Enable nested comments; 7. Adjust comment shape; 8. Use plugins and verification codes to prevent spam comments; 9. Encourage users to use Gravatar avatar; 10. Create comments to refer to

See all articles