Archived topic
Only show year in CPT post date
7 replies · Started by Alvaro on January 26, 2021
Hi,
I have this Books CPT where I want to show just the year in the post meta date.
(I'll use it to show the year the book was published. That way I don't need to add an extra custom field for that.)
What is the GP way of doing it?
Thanks.
You can modify the format of the post date by using the generate_post_date_output filter.
Example:
add_filter( 'generate_post_date_output', function() {
if( ! is_singular( array('page', 'attachment', 'post') ) ){
$time_string = '<time class="entry-date published" datetime="%1$s" itemprop="datePublished">%2$s</time> ';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
$time_string = '<time class="updated" datetime="%3$s" itemprop="dateModified">%4$s</time> ' . $time_string;
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date('Y') ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date('Y') )
);
return sprintf( '<span class="posted-on">%1$s</span>', // WPCS: XSS ok, sanitization ok.
sprintf( '<a href="%1$s" title="%2$s" rel="bookmark">%3$s</a>',
esc_url( get_permalink() ),
esc_attr( get_the_time() ),
$time_string
)
);
}
});
We added the if( ! is_singular( array('page', 'attachment', 'post') ) ) for the filter to not apply on the default post types.
We then simply changed the date format from the default 'c' to 'Y' which only displays the year.
Thank you Elvin.
I had to make some tweeks but it worked.
In this line:
sprintf( '<a href="%1$s" title="%2$s" rel="bookmark">%3$s</a>',
the title="%2$s" was showing a 00:00 string in the frontend.
Also, I had to put this filter before other code I'm using to customize the CPT entry meta.
I'm using this to show two custom taxonomies on this CPT:
add_filter( 'generate_post_date_output', function( $output ) {
if ( 'book_post_type' == get_post_type() ) {
$author = get_the_term_list( get_the_ID(), 'book_author', '<p class="book-author">', ', ', '</p>' );
$genre = get_the_term_list( get_the_ID(), 'book_genre', 'Género: ', ', ' );
// return 'Autores/as: ' . $author . '<br /> Publicação: ' . $output . '<br /> Género: ' . $genre;
return $author . $genre . '<br />Publicação: ' . $output ;
}
else {
return $output;
}
} );
Seems to be working OK. Thanks again.
Good catch.
Nice one. Glad you got it sorted. :D
This seems similar to what I need... can this be modified so that all Blog posts just show MM, YYYY
i.e. currently > February 19, 2021
I need to just show > February, 2021
Many thanks!
Hi William,
Have you tried Dashboard > settings > reading > Date Format, choose Custom, set it to F , Y.
Let me know if it works for you :)
Thank you very much, that worked! I feel silly for not seeing that solution myself.
No problem :)