Home / Archive / “New” Badge for Recent Posts
Duplicate Snippet

Embed Snippet on Your Site

“New” Badge for Recent Posts

Display a badge to highlight posts that are newer than 7 days.

400+
Code Preview
php
<?php
add_filter( 'the_title', function ( $title, $id ) {
	if ( ! is_admin() && is_single( $id ) ) {
		$number_of_days = 7;
		$post_date      = get_the_date( 'U', $id );
		$current_date   = current_time( 'timestamp' );
		$date_diff      = $current_date - $post_date;
		if ( $date_diff < $number_of_days * DAY_IN_SECONDS ) {
			$title .= ' <span class="new-badge">New</span>';
		}
	}
	return $title;
}, 10, 2 );
add_action( 'wp_head', function () {
	echo '
        <style>
            .new-badge {
                background-color: #ff0000; 
                color: #ffffff; 
                padding: 2px 5px; 
                font-size: 12px; 
                border-radius: 3px;
                margin-left: 5px;
            }
        </style>
    ';
} );

Comments

Add a Comment