wordpressfilterwordpress-themingdatemodifiedwordpress-theme-astra

Wordpress Modified Date and Published Date Output


Hope someone can help me output the modified date, or published date if the post is not edited. I'm using the code in Wordpress functions.php file but the output displays the Last Modified date even on new posts.

function astra_post_date()
{
 $format = apply_filters('astra_post_date_format', '');
 $published = esc_html(get_the_date($format));
 $modified = esc_html(get_the_modified_date($format));

$output = '<p class="posted-on">';
if (!empty($modified)) {
$output .= 'Last Modified: <span class="updated" ';
$output .= 'itemprop="dateModified">' . $modified . '</span>';
} else {
$output .= 'Published: <span class="published" ';
$output .= 'itemprop="datePublished">' . $published;
$output .= '</span>';
}
$output .= '</span>';
 
 return apply_filters('astra_post_date', $output);
}

As I've said. I want to show Last Updated: Date if the post was modified. Show the published date if not.


Solution

  • The issue is coming because we are not comparing the publish date and modified date, so the code you are using output the Modified date, because get_the_modified_date() always return the value, even it is equal to publish date, so you can replace your code with the given code in which I have added the condition to compare publish date and modified date, so modified date will show only when they are different.

    function astra_post_date() {
        $format    = apply_filters( 'astra_post_date_format', '' );
        $published = esc_html( get_the_date( $format ) );
        $modified  = esc_html( get_the_modified_date( $format ) );
        $output    = '<p class="posted-on">';
    
        // Here we are checking if the post has been modified.
        if ( $modified && $modified !== $published ) {
            $output .= 'Last Modified: <span class="updated" ';
            $output .= 'itemprop="dateModified">' . $modified . '</span>';
        } else {
            $output .= 'Published: <span class="published" ';
            $output .= 'itemprop="datePublished">' . $published;
            $output .= '</span>';
        }
    
        $output .= '</p>';
    
        return apply_filters( 'astra_post_date', $output );
    }