詳細検索

wp_insert_attachment() with a new insert

Avatar
by すがピー
1 min read

wp_insert_attachment() with a new insert
Translated from 日本語 • View original

The wp_insert_attachment() reference includes

wp_insert_attachment( $attachment, $filename, $parent_post_id );

and you need to specify $parent_post_id. This means that you have to insert something into the posts table beforehand to specify the post_id for that record.

However, if you want to register new image information, but there is no linked post yet, there is no post_id, so I looked into what to do.

I followed the WP source and actually tried it,

wp_insert_attachment( $attachment, $filename, 0 );

$parent_post_id = 0 to insert a new one.

By the way, $attachment has

$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
     'guid'  => $wp_upload_dir['url'] . '/' . basename( $filename ), 
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[ ^.] +$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
);

Just put in the image information of the image you uploaded in advance.

Now, you can register new image information one after another.

Related Articles