Meta Box Date Field Value Custom Format in Bricks

Updated on 3 Apr 2024

Note: A custom function is no longer needed. Use the date format filter, as mentioned in the Bricks documentation.

Ex.:

{{mb_post_event_date:F, Y}}

to get

“Save value as timestamp” need not be ticked/enabled for the Date Picker field.

Date format reference.


This Pro tutorial is similar to the previous ACF Date Field Value Custom Format in Bricks but when using Meta Box and works with both “Date Picker” and “Datetime Picker” type of fields.

Step 0

Tick “Set value as timestamp” for your field.

If your posts already have the dates set, you’d need to edit them and pick the dates again after making the above change.

Step 1

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

// Function to return the given Meta Box date field in the specified format
function bl_get_mb_date( $field_id, $format = 'F j, Y' ) {
	// prevent "Fatal error: Uncaught Error: Call to undefined function rwmb_get_value()" if Meta Box is not active.
	if ( ! function_exists( 'rwmb_meta' ) ) {
		function rwmb_meta( $key, $args = [], $object_id = null ) {
				return null;
		}
	}

	$date_string = rwmb_meta( $field_id );

	if ( $date_string ) {
		return date( $format, rwmb_meta( $field_id ) );
	}

	return '';
}

Set your default date format in

$format = 'F j, Y'

Date format reference

Step 2

To output a date field in the default format set in the function above:

{echo:bl_get_mb_date(banner_start)}

where banner_start is the ID of the custom field.

Sample output: December 14, 2022

Another example:

{echo:bl_get_mb_date(banner_start, Y-m-d)}

outputs 2022-12-14.

Another example:

{echo:bl_get_mb_date(banner_start, l j M Y)}

outputs Wednesday 14 Dec 2022.

Update: If the date field is inside a Group field

Replace the PHP function with:

<?php 

// Function to return the given Meta Box date field inside a group in the specified format
function bl_get_mb_group_date( $group_id, $field_id, $format = 'F j, Y' ) {
	// prevent "Fatal error: Uncaught Error: Call to undefined function rwmb_get_value()" if Meta Box is not active.
	if ( ! function_exists( 'rwmb_meta' ) ) {
		function rwmb_meta( $key, $args = [], $object_id = null ) {
			return null;
		}
	}

	$group = rwmb_meta( $group_id );

	$date_string = $group[ $field_id ]['timestamp'] ?? '';

	if ( $date_string ) {
		return date( $format, $date_string );
	}

	return '';
}

?>

Usage:

{echo:bl_get_mb_group_date(event_group,event_date)}

where event_group is the group ID and event_date is the field ID.

Reference

https://docs.metabox.io/fields/date/#template-usage