I'm using ACF to build blocks.
Here's a simple function I've written via functions.php:
<?php
function my_test_function() {
if ( is_page_template( 'template-parts/blocks/hero/hero.php' ) ) {
echo '<p>I appear via the hero.php template.</p>';
}
if ( is_page_template( 'template-parts/blocks/video/video.php' ) ) {
echo '<p>I appear via the video.php template.</p>';
}
}
?>
Here's how I call the function via hero.php and video.php
<?php
my_test_function();
?>
When I test this, nothing appears. I'm guessing the is_page_template
function doesn't work in this instance as it's technically not a page template.
Is there another function that might work with ACF block templates?
CodePudding user response:
You could use parse_block()
: https://developer.wordpress.org/reference/functions/parse_blocks/ then loop through blocks to check if blockName exist for this page :
function check_if_block_exist($block_handle) {
$post = get_post();
if(has_blocks($post->post_content)) {
$blocks = parse_blocks($post->post_content);
foreach( $blocks as $block ) {
if($block['blockName'] === $block_handle) {
return true;
}
}
return false;
}
}