0

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?

1
  • Hasn't the body_class already been output by this point? It's too late, time travel would be necessary for this code to work as expected. Chances are body_class already has something you can latch on to for this, otherwise you should have asked about your original problem of how to add a class to the body tag using the body_class in a particular scenario, rather than how to fix a proposed solution. How do the templates know to load page-intro.php?
    – Tom J Nowell
    Aug 19 '20 at 8:51
0

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_class action
  • If something had been added, it still wouldn't work because the body_class filter has already ran. It would either need the ability to see into the future to observe that a filter was added to that hook in page-intro.php, or page-intro.php would 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

1
  • Thanks, Tom. You make some excellent points. I'll explore some different options.
    – Sam
    Aug 19 '20 at 9:02

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.