1

I created a block that has an image field and three text boxes: a textfield for the image alt, a text area for the description and another text field that was created in ACF to allow for photo credits to an attached image. The text boxes are mainly there for users to enter metadata for the image and I'm looking for a way to update those metadata when saving a post.

For example: I have a text field called photo_alt_text that's for updating the Alternative text for the attached image. So when a user is saving the post, the text in photo_alt_text is saved to Alternative text.

This is the code I have so far:

function post_extra_save( $post_id, $post){
if ( has_blocks( $post->post_content ) ) {
    $blocks = parse_blocks( $post->post_content );
    foreach ( $blocks as $block ) {
        if ( $block['blockName'] === 'acf/opby-cover-image' ) { // name of block
            $cover_img_photo_alt = $block['attrs']['data']['photo_alt_text']; // text field for `photo_alt_text`
            update_post_meta($post->id, '_wp_attachment_image_alt', $cover_img_photo_alt); // attempting to update the image attachment image alt text
        }
    }
};
}
add_action( 'save_post', 'post_extra_save', 10, 2 );

1 Answer 1

1

I found the problem. It was updating the post instead of the attachment. So instead of $post->ID, I create another string that stores the image ID and replace that with post->ID and it works.

function post_extra_save( $post_id, $post){
if ( has_blocks( $post->post_content ) ) {
$blocks = parse_blocks( $post->post_content );
foreach ( $blocks as $block ) {
    if ( $block['blockName'] === 'acf/opby-cover-image' ) { // name of block
        $media_url_thumb = $block['attrs']['data']['image_post']; // Image ID from the block 
        $cover_img_photo_alt = $block['attrs']['data']['photo_alt_text']; // text field for `photo_alt_text`

        update_post_meta($media_url_thumb, '_wp_attachment_image_alt', $cover_img_photo_alt);
    }
}
};
}
add_action( 'save_post', 'post_extra_save', 10, 2 );
1
  • Ah yes, you're right, I forgot the $post is the post with the block... :p But anyway, that $post->id is still an issue, at least in default WP install, so always use $post->ID.
    – Sally CJ
    Oct 13, 2020 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.