在WordPress文章中显示最后修改日期的3种方法

来自:互联网
时间:2020-03-21
阅读:

对于很多内容我们可能会在不定的时间内进行修改补充,一般情况下我们会忽略这个操作的用户体验,修改补充后WordPress默认还是显示发布日期,而不会显示最后一次/上一次修改更新日期,有时,这不太友好。

您需要将此代码添加到主题的functions.php文件或特定于站点的插件中。

方法1:在内容之前显示上次更新日期

/**
 * @desc 文章最后更新时间/全局
 * @param $content
 * @return string
 */
function my_last_updated_date( $content ) {
	$u_time          = get_the_time( 'U' );
	$u_modified_time = get_the_modified_time( 'U' );
	$custom_content  = '';
	if ( $u_modified_time >= $u_time + 86400 ) {
		$updated_date   = get_the_modified_time( 'Y-m-j h:s a' );
		$custom_content .= '<p class="last-updated entry-meta">最后更新 ' . $updated_date . '</p>';
	}
	$custom_content .= $content;
	return $custom_content;
}
add_filter( 'the_content', 'my_last_updated_date' );

此代码检查文章的发布日期和上次修改日期是否不同。如果是,则显示帖子内容之前的最后修改日期。您可以添加自定义CSS以设置上次更新日期的外观样式。这是一个可以用作起点的小CSS:

.last-updated {
    font-size: small;
    text-transform: uppercase;
    background-color: #fffdd4;
}

在WordPress文章中显示最后修改日期的3种方法

WordPress显示最后更新日期

在WordPress文章中显示最后修改日期的3种方法

WordPress显示最后修改日期

方法2:在主题模板中添加上次更新日期

此方法要求您编辑特定的WordPress主题文件。许多WordPress主题现在使用自己的模板标签来定义这些主题如何显示后期元数据,如日期和时间。

某些主题还使用内容模板或模板部件来显示帖子。

一般的主题将使用single.php,archive.php和其他模板文件来显示内容和元信息。您将查找负责显示日期和时间的代码。然后,您可以使用以下代码替换该代码,或者在主题的日期和时间代码之后添加该代码。

<?php
$u_time          = get_the_time( 'U' );
$u_modified_time = get_the_modified_time( 'U' );
if ( $u_modified_time >= $u_time + 86400 ) {
	echo "<p>Last modified on ";
	the_modified_time( 'Y-m-j h:s a' );
	echo " at ";
	the_modified_time();
	echo "</p> ";
} ?>

显示效果同上。

方法3:如何用上次修改日期替换上次发布的日期

到目前为止,我向您展示的所有方法都处理了除原始发布日期之外的帖子的最后修改日期。

但是,如果您想要将发布日期替换为上次修改日期,该怎么办?嗯,这是可能的,这种方法很好,因为它只显示搜索引擎的最新日期。

<?php $u_time    = get_the_time( 'U' );
$u_modified_time = get_the_modified_time( 'U' );
if ( $u_modified_time >= $u_time + 86400 ) {
	echo "Last updated on ";
	the_modified_time( 'F jS, Y' );
	echo ", ";
} else {
	echo "Posted on ";
	the_time( 'F jS, Y' );
} ?>

此代码将显示:

  • 发布于… [日期],用于尚未更新的帖子
  • 上次更新… [日期]已更新的帖子

修改方法同上。

您应该在您的网站上使用哪种方法?

对于大多数博客来说,我认为第一种方法是最好的,因为它灵活且易于实施。

如果你想要更简单的东西,那么后两个方法都是可靠的选项,尽管它们并不灵活。如果您可以直接编辑主题的模板文件,则最后一种方法只允许显示单个日期,而不是同时显示上次发布的日期和上次修改日期。

返回顶部
顶部