Support

Account

Home Forums Gutenberg Dynamically populating ACF block field values

Unread

Dynamically populating ACF block field values

  • Hi!

    I’ve created an ACF block which is basically a heading with a list of text and images underneath, like

    <section>
    <h2 id="my-heading">My heading</h2>
    <img>
    <p>
    <img>
    <p>
    ...etc.
    </section>

    The ID of “my-heading” is being dynamically set in the block, based on what the user puts in a field called Section Name.

    Now, I would then like to have a Table of Contents block grab those IDs and use them as anchors, so users can quickly navigate to the right section on the page.

    On the internet, I found this piece of code that would help me do that:

    /**
     * Get service sections
     * @link https://www.billerickson.net/access-gutenberg-block-data/
     */
    function ea_get_service_sections() {
    
    	$sections = array();
    
    	global $post;
    	$blocks = parse_blocks( $post->post_content );
    	foreach( $blocks as $block ) {
    		if( 'acf/service' !== $block['blockName'] )
    			continue;
    
    		$title = $anchor = '';
    		if( !empty( $block['attrs']['data']['title'] ) )
    			$title = $block['attrs']['data']['title'];
    
    		if( !empty( $block['attrs']['data']['anchor'] ) )
    			$anchor = $block['attrs']['data']['anchor'];
    
    		if( empty( $anchor ) )
    			$anchor = $title;
    
    		$sections[] = '<a href="' . get_permalink() . '#' . sanitize_title_with_dashes( $anchor ) . '">' . esc_html( $title ) . '</a>';
    	}
    
    	if( empty( $sections ) )
    		return;
    
    	echo '<ul class="service-sections">';
    	foreach( $sections as $section )
    		echo '<li>' . $section . '</li>';
    	echo '</ul>';
    }

    Problem is, in order to use this function to get ACF block data from the $block array, I first have to have my data in the ACF fields for it to pick them up. However, because I set those IDs dynamically using a function in my block template, my IDs never end up as values in the block fields. This means they never end up in the $block array for me to then use in the ToC-block.

    Do you have any idea of how I could go about this? Is there maybe a way I could populate the actual ID field for each block dynamically?

    Any help would be much appreciated!

    Best wishes,
    Lukas

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.