I am trying to create a shortcode to display the CRED post expiry time, formatted as a date, on a single post.
I tried this but I get an error.
(Used this to convert other types fields before)
// Get post expiry date
// Usage: [post-expiry]
function my_post_expiry_time($atts, $content) {
$epoch = get_post_meta( $post_id, '_cred_post_expiration_time', true );
$dt = new DateTime("@$epoch");
$my_expdate = $dt->format('Y-m-d');
return $my_expdate;
}
add_shortcode( 'post-expiry', 'my_post_expiry_time' );
Dear Tina,
Please try to modify your codes as below, and test again:
function my_post_expiry_time($atts, $content) {
$epoch = get_post_meta( get_the_ID(), '_cred_post_expiration_time', true );
$my_expdate = date_i18n( 'Y-m-d', $epoch );
return $my_expdate;
}
add_shortcode( 'post-expiry', 'my_post_expiry_time' );
More help:
https://codex.wordpress.org/Function_Reference/date_i18n
Added a small change to check if there is a post expiry time, because I got an error..
Posting it if anyone needs this.
/* Get post expiry date */
// date_i18n is a WordPress function
// Usage: [post-expiry]
function my_post_expiry_time($atts, $content) {
// get expiry date value
$epoch = get_post_meta( get_the_ID(), '_cred_post_expiration_time', true );
// check if not empty, convert to date, else return nothing
if (!empty($epoch)) {
$my_expdate = date_i18n( 'Y-m-d', $epoch );
} else {
$my_expdate = '';
}
return $my_expdate;
}
add_shortcode( 'post-expiry', 'my_post_expiry_time' );