wordpress最近发布的文章日期变为红色的两种方法

!
也想出现在这里? 联系我们
信息

方法一:

  1. 使用 WordPress 的 get_the_date() 函数来获取文章的发布日期
  2. 然后使用 PHP 的 strtotime() 函数来计算出文章发布的时间戳
  3. 最后使用 PHP 的 date() 函数来格式化日期
  4. 并使用 CSS 来设置文章发布日期的颜色

PHP代码如下:

<?php

$post_date = get_the_date();

$timestamp = strtotime($post_date);

$date = date('Y-m-d', $timestamp);

if (date('Y-m-d') == $date) {

    echo '<span style="color:red;">'.$date.'</span>';

} else {

    echo $date;

}

?>

方法二:

function highlight_today_published_date($the_date) {
    $post_date = get_the_date('Y.m.d'); // 获取文章发布日期,使用"."作为分隔符
    $current_date = date('Y.m.d'); // 获取当前日期,使用"."作为分隔符

    // 检查文章发布日期是否为今日
    if ($post_date === $current_date) {
        // 将字体颜色设置为红色
        $the_date = '<span style="color: red;">' . $the_date . '</span>';
    } else {
        $current_time = strtotime(current_time('Y-m-d')); // 获取当前日期的时间戳
        $post_time = strtotime(str_replace(".", "-", $post_date)); // 替换分隔符并获取文章发布日期的时间戳

        // 检查当前日期是否大于文章发布日期
        if ($current_time > $post_time) {
            // 将字体颜色设置为黑色
            $the_date = '<span style="color: black;">' . $the_date . '</span>';
        }
    }

    return $the_date;
}
add_filter('the_date', 'highlight_today_published_date');
 

2.前端调用日期代码如下:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <p><?php the_date('Y.m.d'); ?></p>
<?php endwhile; endif; ?>

注意事项:

当天发布的文章日期应该以红色标记,过了发布日期后将字体颜色更改为黑色,并且日期的分隔符应为”.”。

上述代码假设日期格式为 Y-m-d,如果你在 WordPress 设置中使用了其他日期格式,请相应地修改代码。

© 版权声明
THE END
喜欢就支持一下吧
点赞160 分享
评论 抢沙发

请登录后发表评论

    请登录后查看评论内容