Support

Account

Home Forums Gutenberg Get an ACF field with a Block from another Post

Unread

Get an ACF field with a Block from another Post

  • There was a question about this back in 2019 but the answers there were unsatisfactory although they offered pointers.

    So…

    If you want to output a field within an acf block on another post;

    (warning, it’s a bit buried)

    
    
    function extract_acf_field( $post_id, $block_name, $field ) {
    
        $post_content = get_post( $post_id );
        $blocks =  parse_blocks( $post_content->post_content );
    
        foreach ($blocks as $block) {
        
            if ( $block_name === $block['blockName'])  {
              foreach ($block['attrs'] as $attr) {
                if (is_array($attr)) {
                    foreach ($attr as $key => $value) {
                        if ($field === $key) {
                            return $value;
                        }
                    }
                }
              }
            }
        }
    }
    
Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.