Menu Close

How to add “New” badge in recent post widgets in WordPress

Codeamend

Let’s see  How to add “New” badge in recent post widgets in WordPress Using shortcode.

Code

Follow the below codes to add “New” badge for the posts that added in last two days. Use Shortcode “badgeposts” to get the results.

function recent_posts_with_badge() {
    
    $args = array(
        'posts_per_page' => 8 
    );
    
    $the_date_today = date('r');
    
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) {
        echo '<div><ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            
            $each_post_date = get_the_time('r');
            $difference_in_days = round( ( strtotime( $the_date_today ) - strtotime( $each_post_date) ) / ( 24 * 60 * 60 ), 0 );
            
            if ( $difference_in_days <= 2 ) {
                echo '<li><a href="' . get_the_permalink() .'">' . get_the_title() .' <span>New</span></a></li>';
            } else { 
                echo '<li><a href="' . get_the_permalink() .'">' . get_the_title() .'</a></li>';
            }

        }
        echo '</ul></div>';
    }
    
    wp_reset_postdata();
}

add_shortcode('badgeposts', 'recent_posts_with_badge'); 

Output

[badgeposts]
Posted in WordPress

You can also read...