wordpress – check attachment existence

I have a function to create an atachment (zip file) in wordpress .

The releveant code is like below :

Read More

My question is : is there a way to CHECK if the same attachment name (or ID or FILE TYPE) exists already before creating a new one ? (meaning before inseting the attachment into the DB..)

At my current state – the attachemnts is created every time that this function runs . Meaning it can create a DB record of a new attachment every tiem – even if the real file is only one file .

$attachment = array(
     'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $path  ), 
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/.[^.]+$/', '', basename($path )),
     'post_content' => '',
     'post_status' => 'inherit'
  );


$attach_id = wp_insert_attachment( $attachment, $path , $post_id); // perform the magic


  require_once(ABSPATH . 'wp-admin/includes/image.php');


  wp_update_attachment_metadata( $attach_id, $attach_data ); // perform the magic II

Related posts

Leave a Reply

1 comment

  1. More context on where your code is happening would’ve been useful…

    Try something like this to check for an attachement existence:

    global $wpdb;
    $title_exists = $wpdb->get_results( 
        $wpdb->prepare( 
            "SELECT ID FROM $wpdb->posts 
            WHERE post_title = '$post->post_title' 
            AND post_type = 'attachment'"
        ) 
    );
    

    Changing post_title = '$post->post_title' for whatever check you need.

    Reference: WordPress StackExchange – Disallow Same Post Title