Backend Development
PHP Tutorial
Optimize the time display of articles and comments in WordPress, wordpress comments_PHP tutorial
Optimize the time display of articles and comments in WordPress, wordpress comments_PHP tutorial
Optimize the time display of articles and comments in WordPress. WordPress comments
Many blogs like to use comments published "XXX minutes ago" and articles published "XXX minutes ago". Displays the time of article comments. The improved time display method not only intuitively tells readers how long it has been since this article or comment was published, but also enhances the time sense of comment replies. I like it very much because I pressed it a while ago. I have too many things at hand, and I suffer from not being able to access the Internet during the day on weekdays, so I have been procrastinating writing the style and functions of the theme bit by bit for a long time. Recently, it is my turn to comment, so I will refer to it step by step. The popular styles on the Internet are modified bit by bit to create their own comment styles and functions.
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:
<?php human_time_diff( $from, $to ) ;?>
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
//将你的评论时间显示的函数改成如下就可以了
<?php echo human_time_diff( get_comment_time('U') , current_time('timestamp')) ;?>
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:
<?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);};
;?>
//将你的评论时间显示的函数改成如下就可以了
<?php echo $cmt_time ;?>
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 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;
The time judgment code is changed to the following:
<?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);};
;?>
//将你的评论时间显示的函数改成如下就可以了
<?php echo $cmt_time ;?>
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 ? $since : $late ;
}endif;
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
Articles you may be interested in:
- Example of using AJAX technology to submit comments in WordPress
- How to use AJAX to asynchronously obtain avatars of comment users in WordPress
- Detailed explanation of the PHP function in WordPress that calls the comment template and loops out comments and the PHP function of the search form
- Solve the error that blog posts cannot be commented after WordPress uses CDN
- Use jQuery to implement the @ID floating display in WordPress to display comment content
- Write a PHP script to Implement the comment pagination function in WordPress
- Example of how to modify the PHP script to enable WordPress to intercept spam comments
- Implement custom default and delayed loading of comment avatars in WordPress
- WordPress Some optimization methods for the visitor comment function
- Implementation of displaying and hiding comments and quote buttons on mouse hover in WordPress
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
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.
10 latest tools for web developers
May 07, 2025 pm 04:48 PM
Web development design is a promising career field. However, this industry also faces many challenges. As more businesses and brands turn to the online marketplace, web developers have the opportunity to demonstrate their skills and succeed in their careers. However, as demand for web development continues to grow, the number of developers is also increasing, resulting in increasingly fierce competition. But it’s exciting that if you have the talent and will, you can always find new ways to create unique designs and ideas. As a web developer, you may need to keep looking for new tools and resources. These new tools and resources not only make your job more convenient, but also improve the quality of your work, thus helping you win more business and customers. The trends of web development are constantly changing.
How to import the source code of wordpress
Apr 20, 2025 am 11:24 AM
Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.
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.
How to add your WordPress site in Yandex Webmaster Tools
May 12, 2025 pm 09:06 PM
Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex
How to set, get and delete WordPress cookies (like a professional)
May 12, 2025 pm 08:57 PM
Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.
How to fix HTTP image upload errors in WordPress (simple)
May 12, 2025 pm 09:03 PM
Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader
How to register a wordpress account
Apr 20, 2025 am 11:45 AM
To create an account on WordPress, simply visit its website, select the registration option, fill in the registration form, and verify your email address. Other ways to register include using a Google account or Apple ID. The benefits of signing up include creating a website, gaining features, joining the community, and gaining support.


