Function and usage of get_post_datetime() in wordpress

Question

Answers ( 1 )

    0
    2024-01-07T15:47:57+00:00

    The get_post_datetime() function in WordPress is a utility for retrieving the published or modified time of a post as a DateTimeImmutable object. This function is particularly useful for theme and plugin developers who need to work with post dates and times in a consistent and reliable manner.

    Function Signature

    get_post_datetime( int|WP_Post $post = null, string $field = 'date', string $source = 'local' ): DateTimeImmutable|false
    

    Function Description

    • Purpose: Retrieves the published or modified time of a post as a DateTimeImmutable object instance.
    • Timezone Handling: The returned object is set to the timezone specified in the WordPress settings.
    • Legacy Support: The function supports both local and UTC time (from the database) for backward compatibility. This is useful in scenarios where timezone settings have changed, potentially causing discrepancies in time values stored in the database.

    Parameters

    1. $post (int|WP_Post, optional): This parameter can be either a post ID or a WP_Post object. If not provided, the function defaults to using the global $post object. The default value is null.

    2. $field (string, optional): Specifies whether to retrieve the post's published ('date') or modified ('modified') time from the database. The default value is 'date'.

    3. $source (string, optional): Determines whether to use local time ('local') or UTC time ('gmt') from the database. The default is 'local'.

    Return Value

    • The function returns a DateTimeImmutable object on success, providing a reliable representation of the post's date or time.
    • Returns false on failure, such as when the post does not exist or the time cannot be retrieved.

    Sample Usage

    // Example 1: Get the published date of the current post in local time
    $date = get_post_datetime(null, 'date', 'local');
    if ($date) {
        echo $date->format('Y-m-d H:i:s');
    }
    
    // Example 2: Get the modified date of a specific post in UTC
    $post_id = 123; // Replace with a specific post ID
    $modified_date = get_post_datetime($post_id, 'modified', 'gmt');
    if ($modified_date) {
        echo $modified_date->format('Y-m-d H:i:s');
    }
    

    In these examples, format('Y-m-d H:i:s') is used to format the date and time. You can adjust the format string as per your requirements.

Leave an answer