I’m using ACF Blocks in a theme I’m building.
Here’s my block template file within /my-plugin/template-parts/blocks/page-intro/page-intro.php:
<?php
/**
* Page Intro 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.
*/
?>
<?php do_action('acf_add_class'); ?>
<div class="page-intro-wrapper" style="background: url(<?php esc_url( the_field('background_image') ); ?> )">
<div class="page-intro">
<h2><?= esc_html( get_field('title') ); ?></h2>
<?= get_field('text'); ?>
</div>
</div>
You’ll see that I’ve added <?php do_action('acf_add_class'); ?> at the top.
I then have the following via my plugin:
/**
* Add custom classes to body
*/
function body_classes( $classes ) {
if ( has_action('acf_add_class') ) {
$classes[] = 'page-intro';
}
return $classes;
}
add_filter( 'body_class', 'body_classes' );
I was hoping that if ( has_action('acf_add_class') ) { would trigger the condition and add the class, but this hasn’t worked.
I’ve also tried this within the body_class filter:
if ( has_action('acf_add_class', get_queried_object_id() ) ) {
$classes[] = 'page-intro';
}
This question may be off-topic if the issue is ACF related.
Any ideas?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
That’s not what has_action does. has_action is true, if functions are added to fire on that hook. It is not a way to detect do_action calls.
However in that code:
- Nothing was added to the
acf_add_classaction - If something had been added, it still wouldn’t work because the
body_classfilter has already ran. It would either need the ability to see into the future to observe that a filter was added to that hook inpage-intro.php, orpage-intro.phpwould need to make changes several microseconds into the past.
Fundamentally, this approach cannot work because the body class has already been generated and sent to the browser. It cannot be fixed, a brand new solution is necessary
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0