Output custom fields using a paragraph block

This code snippet, which you could add to your theme functions.php file or a plugin, will allow you to add a paragraph block to a post and use this to output a custom field.

If you make sure it has a class of meta-value--{meta_key} where {meta_key} is replaced with the key of the meta data you want to retrieve, the block will output the value.

If no value is present, nothing is output.

<?php
/**
 * Re-renders any paragraph block which contains a custom class including "meta-value--"
 *
 * @param string   $block_content The block content.
 * @param array    $block         The full block, including name and attributes.
 * @param WP_Block $instance      The block instance.
 *
 * @return string  $block_content The block content.
 */
function hd_render_post_meta_block( $block_content, $block, $instance ) {

	// if this block doesn't contain a custom class.
	if ( empty( $block['attrs']['className'] ) ) {
		return $block_content;
	}

	if ( ! str_contains( $block['attrs']['className'], 'meta-value--' ) ) {
		return $block_content;
	}

	// create an array of classes from the classes added to the block.
	$classes = explode( ' ', $block['attrs']['className'] );

	// remove the classname at our special class.
	$meta_key = str_replace( 'meta-value--', '', $classes[0] );

	// remove the first class, which is our special class - we don't want this output on the front end.
	unset( $classes[0] );

	global $post;

	// get the registered meta data for this post.
	$registered_meta = get_registered_metadata( 'post', $post->ID );
	
	// if our meta key is not in the registered meta list for this post.
	if ( empty( $registered_meta[ $meta_key ] ) ) {
		return '';
	}

	// get the meta value.
	$meta_value = get_post_meta( $post->ID, $meta_key, true );

	// if we have no meta value.
	if ( empty( $meta_value ) ) {
		return '';
	}

	// add a base class at the start of the classes array.
	$base_class = ['hd-meta-block'];
	$classes = array_merge( $base_class, $classes );

	// start output buffering.
	ob_start();

	?>

	<div class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>"><?php echo esc_html( $meta_value ); ?></div>

	<?php

	// return the cleaned output buffer.
	return ob_get_clean();

}

add_filter( 'render_block_core/paragraph', 'hd_render_post_meta_block', 10, 3 );

Posted

in

by

Tags: