Conditional to check if an instance of a block is the first on page/post (ok)
https://support.advancedcustomfields.com/forums/topic/conditional-to-check-if-an-instance-of-a-block-is-the-first-on-page-post/
Last updated
https://support.advancedcustomfields.com/forums/topic/conditional-to-check-if-an-instance-of-a-block-is-the-first-on-page-post/
Last updated
I have made a cover block with a full size background image and text on top. If this block is inserted as the very first block on a page/post, I wan’t it to display the cover title in <h1> instead of <h2>, so that it acts as a hero block.
This guy made exactly the same question: https://wordpress.stackexchange.com/questions/349050/gutenberg-first-block-on-page-conditional
His code is great, but as he says, if there are more instances of the same block, the changes in his conditional would be made to all of them, and not just the very first instance.
So how can I check if a block is the first on a post/page, and make a change to only that instance?
Here’s a solution I’ve come up with, that works with WordPress 5.4 and ACF Pro 5.8.9.
First you need this function somewhere in functions.php:
This function is used to get the block id of the first block on the page, if this block has a block id. (As far as I can see only ACF blocks have a block id attribute. Core blocks do not).
Now in your block template file you can do this:
$block['id']
is the unique id of every block instance. We then compare it with the id of the first block on the page. If they’re the same, the function will return true, and the title of the post will be displayed.
How i use it I have created a custom cover block with a full size background image and content inside. I wan’t that block to act as a hero element if it’s the very first block on a page.
By using the above method in my block template file, I can display the custom cover block title in a h1 tag instead of h2, if it’s the first block on the page.
I also wan’t to hide the ordinary title and breadcrumb, so that the cover block aligns perfectly to the navigation header. For that I have created this function in my functions.php file:
I can use this as a conditional to check what block type the first block is, and then display or hide the breadcrumb and title accordingly: