admin管理员组

文章数量:1278947

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?

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?

Share Improve this question asked Oct 22, 2021 at 14:00 SamSam 2,1963 gold badges30 silver badges59 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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/access-gutenberg-block-data/#acf-block-data

本文标签: Add page title after first block