CHIPS

制作チップス

Wrordpressで新着記事に一定の期間Newマークをつける

2025年6月14日

カテゴリー: 制作チップス

赤字の部分が、NEWマークを表示させる箇所です。

<ul>
<?php $args = array(
    'post_type' => 'post', // // 投稿タイプ(例: 'post', 'page', 'custom_post_type')
    'posts_per_page' => 10, // 表示する投稿数
    'category_name' => 'news,event', // 取得したいカテゴリーをスラッグで指定
    'category__not_in' => array( 2 ), // 特定のカテゴリーを除外
    'orderby'        => 'date',  // 並び順基準
    'order'          => 'DESC',  // 降順(新しい順)
);
  $the_query = new WP_Query($args); if ($the_query->have_posts() ):
?>
  <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<li>
    <span><?php the_time('Y年m月d日'); ?></span>
    <?php
    // 記事のカテゴリー情報を取得する
    $cat = get_the_category();
    $cat_name = $cat[0]->cat_name; // カテゴリー名
    $cat_slug  = $cat[0]->slug; // カテゴリースラッグ
    ?>
    <span class="<?php echo $cat_slug; ?>"><?php echo $cat_name; ?></span>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php
 $days = 15; // 表示させる期間の日数
 $today = current_time('timestamp');
 $entry = get_the_time('U');
 $elapsed = date('U',($today - $entry)) / 86400;
 if( $days > $elapsed ){
 echo '<span class="new-mark"><div>New</div></span>';
 }
?>
</li>
<?php endwhile; ?>
<?php else: ?>
  <li>投稿がありません。</li>
<?php endif; wp_reset_postdata(); ?>
</ul>

おまけ・・のCSS

凡庸型NEW

New
<span class="new-mark01"><div>New</div></span>

css

.new-mark01{
    display: grid;
    place-items: center;
    width: 40px;
    height: 20px;
    font-size: 1.2rem;
    line-height: 1;
    font-weight: 600;
    background: #de0304;
    color: #fff;
}

ちょっとカワイイNEW

New
<span class="new-mark02"><div>New</div></span>

css

.new-mark02{
    position: relative;
    display: grid;
    place-items: center;
    width: 35px;
    height: 35px;
    border-radius: 50%;
    font-size: 1.2rem;
    font-weight: 600;
    background: #de0304;
    color: #fff;
}
.new-mark02::before{
    content: "";
    position: absolute;
    bottom: -5px;
    left: 35%;
    width: 2px;
    height: 8px;
    transform: rotate(48deg);
    box-sizing: border-box;
    background-color: #de0304;
}

点滅するNEW

New
<span class="new-mark03"><div>New</div></span>
.new-mark03{
    display: grid;
    place-items: center;
    width: 40px;
    height: 20px;
    font-size: 1.2rem;
    line-height: 1;
    font-weight: 600;
    background: #de0304;
    color: #fff;
    animation: flash 1s linear infinite;
}
@keyframes flash {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}