One day I needed to create a WordPress attachment programmatically. Turns out there are some things to remember, and some mysteries as well.
The way to start creating an attachment is using the wp_insert_attachment() function like this:
wp_insert_attachment( $attachment, $filename, $parent_post_id );
The three parameters should be an array, a string and an integer. But, it’s important to remember that the $attachment
array must contain the following:
post_title => 'The Post Title string'
,
post_content => ''
(an empty string),
post_status => 'valid_post_status_name'
(this should actually be ‘inherit’) and
post_mime_type=> 'image/jpg'
(for example).
It’s very easy to forget some of them, like the empty post_content or the mime_type. If you don’t provide all these, the function will fail.
The WordPress Codex helpfully tells you about the return values for this function: “Returns the resulting post ID (int) on success – likely returns 0 on failure.” (emphasis added)
The return values for the function according to the WordPress Codex are as follows:
Returns the resulting post ID (int) on success or 0 (int) on failure.
The next steps are:
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data );
A future post I’ll set up tells what this functions actually do and some caveats!