How to integrate get_post_time with date_i18n function?

The question:

I have date format and would like to translate to another language with date_i18n function how can I integrate with get_post_time here is my code :

$time = get_post_time('F j, Y', true,$newspost['ID']);

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Use the fourth parameter for get_post_time():

$time = get_post_time(
    'F j, Y',      // format
    TRUE,          // GMT
    get_the_ID(),  // Post ID
    TRUE           // translate, use date_i18n()
);

get_post_time() calls mysql2date() internally, and it passes the $translate argument through. In mysql2date() we find this:

if ( $translate )
    return date_i18n( $format, $i );

So, all you need is a single TRUE.

For a test, try this:

add_filter( 'the_content', 'wpse_100266_i18n_time' );

/**
 * Prepend the post content with translated post time.
 *
 * @wp-hook the_content
 * @param   string $content
 * @return  string
 */
function wpse_100266_i18n_time( $content )
{
    $time = get_post_time(
        'F j, Y',      // format
        TRUE,          // GMT
        get_the_ID(),  // Post ID
        TRUE           // translate, use date_i18n()
    );

    return "<p>$time</p>$content";
}

Then install at least one other language and the plugin WCM User Language Switcher. Viewing the front end, we get different month names when we switch the language now.

get_post_modified_time() works with the same arguments.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment