Вопрос

I have a way to set a thumbnail for a post if a checkbox is selected or not. The problem I'm having is if the checkbox is selected and then unselected, how do you delete the featured image that was set? I.E. remove the featured image. I tried to do set_post_thumbnail($post->ID, ''); with the '' blank to remove the image but that didn't work.

My code in my functions.php:

function post_extra_save( $post_id, $post){
if ( has_blocks( $post->post_content ) ) { // get blocks 
    $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
            $check_if_featured = $block['attrs']['data']['set_featured_image'][0]; // check if checkbox is selected, will say 'sfi' is enabled
            if ($check_if_featured == 'sfi') { // if checkbox is selected
                set_post_thumbnail($post->ID, $media_url_thumb);
            } else { // if checkbox is not selected
                set_post_thumbnail($post->ID, '');
            }
        }
    }
};
}
add_action( 'save_post', 'post_extra_save', 10, 2 );
Это было полезно?

Решение

No, you can't use set_post_thumbnail() to remove the post thumbnail. The function you need is delete_post_thumbnail().

// Both of these work.
delete_post_thumbnail( $post->ID ); // pass the post ID
//delete_post_thumbnail( $post );   // or post object
Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top