phpwordpresswordpress-themingwordpress-gutenberggenesis

How to add an image dynamically to post title if it is published today or less than 2 days


I was trying to add an image like a "new" image to the posts which are just published and are less than 2 days old.

I tried using a function like this within a WP_Query but it is applying to all posts.

add_action('the_title', 'insiderable_add_img_new');
function insiderable_add_img_new($title) {
    $title = '<img src="https://example.com/icon.gif">'.$title;
    return $title;
}

This is what I tried with WP_Query:

$events_query = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'posts_per_page'=>-1)); 
if($events_query->have_posts()) : 
    while($events_query->have_posts()) : 
       $events_query->the_post();
       if (get_the_date( 'Y-m-d' ) === date( 'Y-m-d' )) {
        add_filter('the_title', 'insiderable_add_img_new');
    }
endwhile; else: endif;
wp_reset_postdata();
function insiderable_add_img_new($title) {
    $title = '<img src="https://example.com/icon.gif">'.$title;
    return $title;
}

Solution

  • This code snippet checks for all posts and if the date matches today, it modifies the $title.

    I am looking for a more efficient code, please suggest if you have one.

    Place this snippet in the functions.php at the bottom:

    // Working Model 
    add_filter( 'the_title', 'ag_custom_post_title_link' );
    function ag_custom_post_title_link( $title ) {
        $postdate = get_the_date( 'Y-m-d' );
    $nows = date( 'Y-m-d' );
        if ( $postdate == $nows) {
            $title = '<img src="https://example.com/img.gif">'.$title;
        }
        return $title;
    }
    

    You can also edit it to apply: if the post is less than 2 days old or something like that.

    I think that helps someone :)