1

I'm printing the last modified date via functions.php with the following code

function wpb_last_updated_date( $content ) {
    $u_time = get_the_time('U'); 
    $u_modified_time = get_the_modified_time('U'); 
    if ($u_modified_time >= $u_time + 86400) { 
        $updated_date = get_the_modified_time('F jS, Y');
        $updated_time = get_the_modified_time('h:i a'); 
        $custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';  
    } 

    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );

The problem is that it appears on pages too, but I need to appear only on posts. Is there an if command to choose only blog posts? Thanks

0

You can check the post type with get_post_type(). You only want to display the content if the value is post:

function wpb_last_updated_date( $content ) {
    $u_time          = get_the_time( 'U' ); 
    $u_modified_time = get_the_modified_time( 'U' ); 

    if ( get_post_type() === 'post' ) {
        if ( $u_modified_time >= $u_time + 86400) { 
            $updated_date   = get_the_modified_time( 'F jS, Y' );
            $updated_time   = get_the_modified_time( 'h:i a' ); 
            $custom_content = '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
        }
    }

    $custom_content .= $content;

    return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
0

All you have to do is to check, if current post is a post and not a page:

function wpb_last_updated_date( $content ) {
    if ( 'post' != get_post_type() ) return $content;

    $u_time = get_the_time('U'); 
    $u_modified_time = get_the_modified_time('U'); 
    if ($u_modified_time >= $u_time + 86400) { 
        $updated_date = get_the_modified_time('F jS, Y');
        $updated_time = get_the_modified_time('h:i a'); 
        $custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';  
    } 

    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
  • 1
    get_the_ID() is redundant here. get_post_type() checks the same global post that get_the_ID() does. – Jacob Peattie Feb 15 at 9:10
  • @JacobPeattie Yup, you're right. Good catch. – Krzysiek Dróżdż Feb 15 at 9:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.