• Resolved ferda2

    (@ferda2)


    Hi, I need to modify a value from a custom field (CF7_get_custom_field key=’my_date’). Now it shows (example): 20240214. I need the format 14.2.2024. Thank you for the advice.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hello! You’ll need a custom shortcode to convert the format for you. Try this code snippet:

    /**
     * Get Date in Custom Format
     *
     * Custom shortcode for Contact Form 7 - Dynamic Text Extension
     *
     * @see https://www.ads-software.com/support/topic/get-dynamic-start-date-of-an-event/
     * @see https://www.php.net/manual/en/datetimeimmutable.createfromformat.php
     *
     * @return string The date formatted as d.m.Y or an empty string on failure.
     */
    function ferda2_custom_date()
    {
        // Call the CF7_get_custom_field function directly, returns date formatted as YYYYMMDD e.g 20240214
        $date = wpcf7dtx_get_custom_field(array('key' => 'my_date'));
        if ($date) {
            // Convert string to DateTime object
            $date = date_create_from_format('YYYYMMDD', $date, new DateTimeZone(wp_timezone_string()));
            if ($date !== false) {
                // Return with desired format e.g. 14.2.2024
                return $date->format('d.m.Y');
            }
        }
        return ''; // Return empty string on failure
    }
    add_shortcode('ferda2_custom_date', 'ferda2_custom_date');

    And in the form template, update the form tag to use your custom shortcode instead: [dynamic_text my_date "ferda2_custom_date"]

    Cheers!

    Thread Starter ferda2

    (@ferda2)

    Hi Tessa, thank you for answer! I found that [dynamic_text date “acf field=’my_date'”] also works and the date formatting is correct (according to ACF settings).

    Ah, you’re using ACF! Yes, you can define the outputted format directly in the ACF edit screen for that field under General > Return Format (see documentation). That also makes sense because it says that the value is saved as Ymd (e.g. “YYYYMMDD”) in the database which is why grabbing the raw value using our built-in shortcode returns it in that format.

    Also, this made me notice the typo in my above code where I wrote

    $date = date_create_from_format('YYYYMMDD', $date, new DateTimeZone(wp_timezone_string()));

    that needed to be

    $date = date_create_from_format('Ymd', $date, new DateTimeZone(wp_timezone_string()));

    Your solution is a great one. If you have the format you want configured in the ACF setting, you can use the ACF shortcode in our form tags ??

    Since you’re using a custom format, the dynamic_text or dynamic_hidden form tags are more suitable for your case since HTML date inputs requires RFC 3339 specification, so only Y-m-d (e.g. “YYYY-MM-DD”) is valid for that form tag.

    Glad it’s sorted. Cheers!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Value from custom field (date)’ is closed to new replies.