0

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 );

1 Answer 1

1

I believe you can just check if the post status is trash, and if so, don't run the rest of your code. E.g. (PS: I intentionally used strict comparison, i.e. using === as in $pagenow === 'post.php')

function post_extra_save( $post_id, $post ) {
    global $pagenow;
    if ($pagenow === 'post.php' && 'trash' !== $post->post_status) {
        ... your code.
    }
}

Alternatively, run your code only if the post status is publish or that it's in one of a whitelisted/allowed statuses list. E.g.

function post_extra_save( $post_id, $post ) {
    global $pagenow;

    $allowed_statuses = array( 'publish', 'private' ); // list of allowed post statuses

    if ($pagenow === 'post.php' && in_array( $post->post_status, $allowed_statuses )) {
        ... your code.
    }
}
1
  • 1
    Awesome! I knew there was a way to execute functions on published posts. Thanks for the help. Jun 11 at 1:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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