Domanda

I use a Wordpress Theme where the format date and time is directly coded in 2 formats :

<?php the_time('d M'); ?>

<?php the_time('H:i'); ?>

What I want :

  • Display the date and the time as defined in wordpress options
  • I don't want to create modified templates in the Child Theme
  • I prefer to use functions.php for that

I've already added in functions.php this code that works :

add_filter( 'the_time', 'changer_date_format', 10, 1 ); //override time display
function changer_date_format( $ladate ) {
    global $post;
    $ladate = get_post_time( get_option( 'date_format' ), false, $post, true ); 
    return $ladate;
} 

But the problem with this solution is that I can just apply either the date or the time wordpress option for the 2 cases the_time('d M') and the_time('H:i'), and I would like to apply separately:

  • the TIME wordpress option on the case the_time('H:i')
  • the DATE wordpress option for the case the_time('d M')
È stato utile?

Soluzione

As per the code reference the_time filter recieves two parameters - $get_the_time and $format. You can use the latter to determine which formatting option to use.

add_filter( 'the_time', 'changer_date_format', 10, 2 );
function changer_date_format( $ladate, $format ) {
  global $post;
  if ( 'd M' === $format ) {
    return get_post_time( get_option( 'date_format' ), false, $post, true ); 
  } else if ( 'H:i' === $format ) {
    return get_post_time( get_option( 'time_format' ), false, $post, true ); 
  } else {
    return $ladate;
  }  
} 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top