12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Feb 17, 2022

Custom Field Image For Media Thumbnail in WP Grid Builder

Sridhar Katakam

Looking to replace the featured image in Card Media with the value of an image-type custom field when using WP Grid Builder?

Here’s the code for that, thanks to Loïc Blascos – the developer of WPGB.

add_filter( 'wp_grid_builder/grid/the_object', function( $object ) {
	$image = get_post_meta( $object->ID, 'card_image', true );

	if ( ! empty ( $image ) ) {
		$object->post_thumbnail = $image;
	}

	return $object;
}, 10, 1 );

where card_image is the

  • field name with Return Format set to Image ID when using ACF or,
  • field ID when using Meta Box

Code can be added using a plugin like Code Snippets.

With this in place, the image in the Card Media will be taken from your custom field’s value if present, otherwise the standard featured image will be used.

Update: If you wish to limit this to a particular grid use this code instead:

add_filter( 'wp_grid_builder/grid/the_object', function( $object ) {
	$grid = wpgb_get_grid_settings();

	if ( 1 === (int) $grid->id ) {
		$image = get_post_meta( $object->ID, 'card_image', true );

		if ( ! empty ( $image ) ) {
			$object->post_thumbnail = $image;
		}
	}

	return $object;
}, 10, 1 );

where 1 is the ID of the grid.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-ocalendar-check-omagnifiercrossmenuchevron-downarrow-right