I have a code that downloads an image and saves it to the media library when you save a post that uses a certain block. The code runs perfect but downloads the image again if you delete the post. How do you prevent media
_sideload_image` from running when you delete a post?
My code :
function post_extra_save( $post_id, $post){
global $pagenow;
if ($pagenow == 'post.php') { // if creating a new post
if ( has_blocks( $post->post_content ) ) {
$blocks = parse_blocks( $post->post_content );
foreach ( $blocks as $block ) {
if ( $block['blockName'] === 'acf/opby-link' ) { // if block is used
static $updated = false;
// If title has already been set once, bail.
if ( $updated ) {
return;
}
// Since we're updating this post's title, set this
// variable to true to ensure it doesn't happen again.
$updated = true;
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$url = "https://cdn.pixabay.com/photo/2022/04/08/21/04/buildings-7120297_1280.jpg";
media_sideload_image($url, $post_id, null, 'id');
}// End if check opby-video.
}
}
}
}
add_action( 'save_post', 'post_extra_save', 10, 2 );