首页 文章

Wordpress - 将上传的图片附加到帖子

提问于
浏览
0

我正在使用Wordpress插件Alchimist Ajax Upload通过Ajax上传图像,在提交表单后和上传未附加的图像后创建帖子 . 我的问题是我需要将上传的图像附加到创建的帖子上 . 我有帖子ID和附件ID,是否有一个php方法,我可以编写,只使用他们的ID附加这两个?谢谢你能得到任何回应 .

1 回答

  • 2

    没试过 . 但也许你可以用它 . 从codexget_attached_file功能结合得到它

    // the ID of the attachment
    $filename = get_attached_file( $attachment_id ); // Full path
    
    // The ID of the post this attachment is for.
    $parent_post_id = 37;
    
    // Check the type of file. We'll use this as the 'post_mime_type'.
    $filetype = wp_check_filetype( basename( $filename ), null );
    
    // Get the path to the upload directory.
    $wp_upload_dir = wp_upload_dir();
    
    // Prepare an array of post data for the attachment.
    $attachment = array(
      'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
      'post_mime_type' => $filetype['type'],
      'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
      'post_content'   => '',
      'post_status'    => 'inherit'
    );
    
    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
    
    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    
    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    

相关问题