## Update a text field in a block when saving a post?

Question

I’m updating my theme to work with Gutenberg and I’m having a problem updating a text field in a block when saving a post.

In my old theme, I had a function that updated a text field in a metabox when saving a post using update_post_meta. It takes the data in a text field and updates it to something else. I tried to do the same for a block but it didn’t update.

Is there a way to update a text field in a block using update_post_meta when saving a post?

Here’s my code:

// function
function post_extra_save( $post_id,$post){

// get blocks
if ( has_blocks( $post->post_content ) ) {$blocks = parse_blocks( $post->post_content ); foreach ($blocks as $block ) { // the block if ($block['blockName'] === 'acf/opby-video' ) {
// extract the data from the text field and separate it using explode
$media_video_url = explode('/',$block['attrs']['data']['youtube_url']);
// if explode matches
if ($media_video_url[2] == 'www.youtube.com') {$new_vid_embed_2_raw = str_replace("watch?v=","",$media_video_url[3]);$new_vid_embed_2_check = 'https://www.youtube.com/watch?v='.$new_vid_embed_2_raw;$new_vid_embed_2 = 'https://www.youtube.com/embed/'.$new_vid_embed_2_raw; // update the text field when saving if ($new_vid_embed_2 && get_post_meta( $post->ID, 'youtube_url', true ) !==$new_vid_embed_2_check) {
update_post_meta( $post->ID, 'youtube_url',$new_vid_embed_2 );
}
};
}
}
};
}
add_action( 'save_post', 'post_extra_save', 10, 2 );

0
8 months 2020-12-12T18:10:39-05:00 0 Answers 32 views 0