0

I have this conditional statement that checks if an image has been added to a custom post type and if it hasn't it inserts a default image.

if ( get_post_meta( get_the_ID(), 'team_page_custom_image', true ) ) {

echo wp_get_attachment_image($post_meta_data['team_page_custom_image'][0], 'medium');  
    }  
    else {
        echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/img/team-logo.png" />';
    }

It seems works fine except when an image is chosen and then deleted from the media library it leaves a blank spot as there is still a meta value in the database for the post-meta.

I know I can just delete them from the database but is there a function somewhere to take care of orphans from media library deletions?

0

Maybe it can be solved at run-time. wp_get_attachment_image says:

Returns an HTML image element representing an attachment file, if there is any, otherwise an empty string.

So, if the post meta is set, but an empty string is given, we should delete the post meta.

$default = '<img src="' . get_stylesheet_directory_uri() . '/img/team-logo.png" />';

if ( get_post_meta( get_the_ID(), 'team_page_custom_image', true ) ) 
{
    $get_img = wp_get_attachment_image( $post_meta_data['team_page_custom_image'][0], 'medium' );  

    if( !emtpy( $get_img ) )
    {
        echo $get_img;
    }
    else
    {
        delete_post_meta( get_the_ID(), 'team_page_custom_image' );
        echo $default;
    }
}  
else 
{
    echo $default;
}

Or you can create a routine with get_posts() (in some hook or Settings API) to iterate through all posts and check/delete orphans.

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.