wp_insert_attachment()


WordPressのwp_insert_attachment()関数は、メディアライブラリに添付ファイルを登録するために使用されます。この関数は、新しい投稿として添付ファイルを追加し、指定した投稿に関連付けることができます。

シンタックス

wp_insert_attachment( array $args, string $file = '', int $parent = 0, bool $wp_error = false );

引数の説明:

  • $args (array) — 添付ファイルの詳細情報を含む配列。例えば、post_titlepost_contentなど。
  • $file (string) — アップロードされたファイルのパス。
  • $parent (int) — 親投稿ID。デフォルトは0(関連付けなし)。
  • $wp_error (bool) — エラーが発生した場合にWP_Errorを返すかどうか。デフォルトはfalse

例 1: シンプルな添付ファイルの追加

添付ファイルを投稿に関連付けずに登録する基本的な例です。

<?php
$args = array(
    'post_title' => 'Sample Attachment',
    'post_content' => '',
    'post_status' => 'inherit',
    'post_mime_type' => 'image/jpeg',
);
$file_path = wp_upload_dir()['path'] . '/sample-image.jpg';
wp_insert_attachment( $args, $file_path );
?>

例 2: 親投稿に添付ファイルを追加

親投稿IDを指定して添付ファイルを追加します。

<?php
$parent_id = get_the_ID();
$args = array(
    'post_title' => 'Attached Image',
    'post_content' => '',
    'post_status' => 'inherit',
    'post_mime_type' => 'image/png',
);
$file_path = wp_upload_dir()['path'] . '/attached-image.png';
wp_insert_attachment( $args, $file_path, $parent_id );
?>

例 3: エラーハンドリング付きの添付ファイル登録

WP_Errorを返す設定でエラー処理を行います。

<?php
$args = array(
    'post_title' => 'Error Handling Example',
    'post_content' => '',
    'post_status' => 'inherit',
    'post_mime_type' => 'image/jpeg',
);
$file_path = wp_upload_dir()['path'] . '/error-example.jpg';
$result = wp_insert_attachment( $args, $file_path, 0, true );
if ( is_wp_error( $result ) ) {
    echo $result->get_error_message();
}
?>

例 4: アップロード後に添付ファイルを登録

wp_handle_upload()関数を使用してファイルをアップロードした後に添付します。

<?php
$uploaded_file = wp_handle_upload( $_FILES['file'], array( 'test_form' => false ) );
if ( isset( $uploaded_file['file'] ) ) {
    $args = array(
        'post_title' => 'Uploaded Attachment',
        'post_content' => '',
        'post_status' => 'inherit',
        'post_mime_type' => $uploaded_file['type'],
    );
    wp_insert_attachment( $args, $uploaded_file['file'] );
}
?>

例 5: 添付ファイルのメタデータを更新

添付ファイルを登録した後にメタデータを生成します。

<?php
$args = array(
    'post_title' => 'Attachment with Metadata',
    'post_content' => '',
    'post_status' => 'inherit',
    'post_mime_type' => 'image/jpeg',
);
$file_path = wp_upload_dir()['path'] . '/metadata-image.jpg';
$attachment_id = wp_insert_attachment( $args, $file_path );
if ( ! is_wp_error( $attachment_id ) ) {
    require_once ABSPATH . 'wp-admin/includes/image.php';
    wp_generate_attachment_metadata( $attachment_id, $file_path );
}
?>

注意点

wp_insert_attachment()関数を使用する際は、require_once ABSPATH . 'wp-admin/includes/image.php';を読み込むことでメタデータの生成を忘れないようにしてください。


関連機能: