wp_insert_attachement没有在wordpress中返回值

时间:2016-03-18 08:30:05

标签: php wordpress

在这里,我使用wp_insert_attachment函数将图像附加到post(自定义字段),但遗憾的是我没有从wp_inset_attachment函数获取附件ID。这是我的代码。

function jda_upload_image( $file = array() ) {
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );

      $file_return = wp_handle_upload( $file, array('test_form' => false ) );

      if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
          return false;
      } else {

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

          $attachment_id = wp_insert_attachment( $attachment, $file_return['url']);
          /* Here I am not getting the attachment_id */

          require_once(ABSPATH . 'wp-admin/includes/image.php');
          $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
          wp_update_attachment_metadata( $attachment_id, $attachment_data );

          if( 0 < intval( $attachment_id ) ) {
            return $attachment_id;
          }
      }
      return false;
}

1 个答案:

答案 0 :(得分:1)

需要时间。我试过你的代码,但卡住了。所以我用以下代码做到了。这对我来说可以。也许对你有用。
根据您的要求更改代码。

    $file = $_FILES['logo']; 
    if(!empty($file)) {
    handle_logo_upload($file);

    }
    function handle_logo_upload($file){
    if ( !function_exists( 'wp_handle_upload' ) ) {
      require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }
    require_once ( ABSPATH . 'wp-admin/includes/image.php' );


    $uploadedfile = $file;
    $upload_overrides = array( 
      'test_form' => false,
      );
    if(!empty($uploadedfile['name'])) {
      $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
      if ( $movefile ) {
        $wp_filetype = $movefile['type'];
        $filename = $movefile['file'];
        $wp_upload_dir = wp_upload_dir();
        $attachment = array(
          'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
          'post_mime_type' => $wp_filetype,
          'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
          'post_content' => '',
          'post_status' => 'inherit'
          );
        $attach_id = wp_insert_attachment( $attachment, $filename);
        $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
        wp_update_attachment_metadata( $attach_id, $attach_data );
        echo '<br>';
        var_dump($uploadedfile);
        return "pass";
      }
    }
    return "fail";
    }