0

I'm building a theme that uses native and custom ACF blocks.

At the top of my default page.php template, I have the following:

<?php
if ( has_post_thumbnail() ) {
    the_post_thumbnail();
}
?>

<header class="entry-header">
    <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header>

<?php the_content(); ?>

If a featured image is uploaded, the page title sits nicely underneath.

However, if no featured image is uploaded and a cover block (for example) is added, the page title obviously sits on top of the block.

Is there a condition I can use that always inserts the page title underneath the first block added if no featured image is uploaded?

0

The only I can think of is to use [parse_block()][1] and [render_block()][1]

parse_block will parse html blocks into an array, and render_block will convert an array into content.

Here is an example of how you can achieve what you want using the above functions (code not tested):

<?php
if (has_post_thumbnail()) {
    the_post_thumbnail();
}
?>

<?php
if (has_post_thumbnail()) {
?>
   <header class="entry-header">
        <?php
            the_title('<h1 class="entry-title">', '</h1>');
        ?>
   </header>
<?php
}
?>

<?php
$renderd_content = "";
$parsed_blocks   = parse_blocks($post->content);
foreach ($parse_blocks as $block_index => $block_attr) {
    if ($block_index === 1 && !has_post_thumbnail()) {
        $renderd_content .= the_title('<h1 class="entry-title">', '</h1>', false);
    }
    $renderd_content .= render_block($block_attr);
}

echo $renderd_content;
?>

Here is a link that provides more examples of this and discuss ACF as well. https://www.billerickson.net/access-gutenberg-block-data/#acf-block-data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.