「已注销」 2019-04-30 16:45 采纳率: 0%
浏览 197

wordpress 怎么让最近一天的文章日期显示为红色呢?

wordpress 怎么让最近一天的文章日期显示为红色呢?
以前的文章日期显示为灰色,
5.1号发布的为红色,5.1之前的为灰色,明天发布的时候,5.2号发布的文章日期显示红色,5.1及之前的显示为灰色

  • 写回答

1条回答 默认 最新

  • 一只小爪磕 前端领域新星创作者 2024-05-23 10:52
    关注

    本答案由爪磕协同GPT-4o回答,希望对您有所帮助 解决问题望采纳!


    要实现最近一天的文章日期显示为红色,之前的文章日期显示为灰色,可以通过WordPress的模板结合JavaScript或jQuery来实现。以下是具体的步骤:

    1. 修改WordPress模板

    首先,需要在WordPress模板文件中添加一个自定义类,以便区分日期。假设我们在循环中输出文章日期时,添加一个自定义类 post-date

    <?php
    // The Loop
    if ( have_posts() ) :
        while ( have_posts() ) : the_post(); ?>
            <div class="post">
                <h2><?php the_title(); ?></h2>
                <p class="post-date" data-date="<?php echo get_the_date('Y-m-d'); ?>"><?php echo get_the_date(); ?></p>
                <div class="entry">
                    <?php the_content(); ?>
                </div>
            </div>
        <?php endwhile;
    else :
        echo '<p>No posts found</p>';
    endif;
    ?>
    

    2. 添加CSS样式

    在你的主题的CSS文件(通常是 style.css)中添加样式。

    .post-date {
        color: gray;
    }
    
    .post-date.recent {
        color: red;
    }
    

    3. 添加JavaScript/jQuery代码

    在你的主题的JavaScript文件(通常是 scripts.js)中添加以下代码。确保你的WordPress主题已经包含了jQuery。

    jQuery(document).ready(function($) {
        // 获取当前日期
        var currentDate = new Date();
        currentDate.setHours(0, 0, 0, 0); // 将时间部分置零
    
        $('.post-date').each(function() {
            // 获取文章发布日期
            var postDateStr = $(this).data('date');
            var postDate = new Date(postDateStr);
            postDate.setHours(0, 0, 0, 0); // 将时间部分置零
    
            // 比较日期
            if (postDate.getTime() === currentDate.getTime()) {
                $(this).addClass('recent');
            }
        });
    });
    

    4. 确保JavaScript文件加载

    确保你的JavaScript文件在主题中被正确加载。一般在主题的 functions.php 中添加如下代码:

    function theme_enqueue_scripts() {
        // Enqueue your main stylesheet
        wp_enqueue_style('main-stylesheet', get_stylesheet_uri());
    
        // Enqueue jQuery (if not already included by WordPress)
        wp_enqueue_script('jquery');
    
        // Enqueue your custom JavaScript file
        wp_enqueue_script('custom-scripts', get_template_directory_uri() . '/scripts.js', array('jquery'), false, true);
    }
    add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
    

    通过以上步骤,你就可以实现最近一天的文章日期显示为红色,之前的文章日期显示为灰色的效果。每次刷新页面时,JavaScript会自动检查日期并根据需要应用相应的样式。

    评论
编辑
预览

报告相同问题?