jackfearing
2/29/2020 - 1:40 AM

WordPress: Gutenberg Block / ACF Relationship Field

<?php
/**
 * Block template file: template-parts/blocks/sidebar/sidebar-headline.php
 *
 * Sidebar Headline Block Template.
 *
 * @param   array $block The block settings and attributes.
 * @param   string $content The block inner HTML (empty).
 * @param   bool $is_preview True during AJAX preview.
 * @param   (int|string) $post_id The post ID this block is saved to.
 */

// Create id attribute allowing for custom "anchor" value.
$id = 'sidebar-headline-' . $block['id'];
if ( ! empty($block['anchor'] ) ) {
    $id = $block['anchor'];
}

// Create class attribute allowing for custom "className" and "align" values.
$classes = 'block-sidebar-headline';
if( ! empty( $block['className'] ) ) {
    $classes .= ' ' . $block['className'];
}
if( ! empty( $block['align'] ) ) {
    $classes .= ' align' . $block['align'];
}
?>

<style type="text/css">
	<?php echo '#' . $id; ?> {
		/* Add styles that use ACF values here */
	}
</style>

<div id="<?php echo esc_attr( $id ); ?>" class="<?php echo esc_attr( $classes ); ?>">
	<?php the_field( 'sidebar_headline' ); ?>
	
	<?php // Make sure to set ACF Relationship field to POST ID ?>
	<?php $sidebar_relationship = get_field( 'sidebar_relationship' ); ?>
	<?php if ( $sidebar_relationship ): ?>
		<?php foreach ( $sidebar_relationship as $p ): ?>
			<a href="<?php echo get_permalink( $p ); ?>"><?php echo get_the_title( $p ); ?></a>
			<?php //echo get_post_field('post_content', $p);?>
			
			<?php // https://wordpress.stackexchange.com/questions/9667/get-wordpress-post-content-by-post-id
				$content_post = get_post($p);
				$content = $content_post->post_content;
				$content = apply_filters('the_content', $content);
				$content = str_replace(']]>', ']]&gt;', $content);
				echo $content;
			?>
		<?php endforeach; ?>
	<?php endif; ?>
</div>