php – Add number class that iterates in Gutenberg blocks wordpress

exception or error:

I am using a custom block for Gutenberg

add_action('acf/init', 'my_acf_init');
function my_acf_init() {

    if( function_exists('acf_register_block') ) {

        acf_register_block(array(
            'name'              => 'h2-block',
            'title'             => __('H2 Block'),
            'description'       => __('A custom H2 block.'),
            'render_callback'   => 'h2_block_render_callback',
            'category'          => 'formatting',
            'icon'              => 'admin-comments',
            'supports' => array(
                'align' => array( 'left', 'right' ),
            ),
        ));

    }
}

Render callback

function h2_block_render_callback( $block ) {
    $className ='h2-block';

    if (!empty($block['className'])) {
            $className = ''. $block['className'];
    }
    if( !empty($block['align']) ) {
        $className .= ' has-text-align-' . $block['align'];
    }
    ?>
    <div class="section_one <?php echo esc_attr($className); ?> <?php echo h2_block_class(); ?>">
        <?php echo '<h2>'.get_field('h2_content').'</h2>'; ?>
    </div>
    <?php
}

This allows me to use a custom block using Gutenberg and is rendering fine

below is the code I am using to iterate and add class to the blocks which is not working

function h2_block_class() {
    global $post;
    $blocks = parse_blocks( $post->post_content );
    $i = 0;
    foreach ( $blocks as $block ) {
        if ($block['blockName'] == 'acf/h2-block') {
            $i++;
            $total_blocks = $i;
        }
    }
    return $total_blocks;
}

The result displays wrong

<div class="section_one h2-block 2"><h2>Header 1</h2></div>
<div class="section_one h2-block 2"><h2>Header 2</h2></div>

Where it should be

<div class="section_one h2-block 1"><h2>Header 1</h2></div>
<div class="section_one h2-block 2"><h2>Header 2</h2></div>
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *