将图像上传到wordpress并在db中保存详细信息

时间:2015-10-13 18:18:36

标签: php wordpress automation

我想通过一个完全在wordpress之外的php脚本将图像上传到wordpress。我知道我必须将数据插入到哪些表中。但是我注意到,如果我通过正常方式,wordpress会创建各种大小的图像,并将其保存在db中。有没有办法在WordPress之外使用脚本模拟图像的上传。

1 个答案:

答案 0 :(得分:3)

是的,它会是这样的:

<?php
    header('Response: HTTP/1.1 200 OK');
    define('WP_USE_THEMES', false);
    require('../../../../wp-load.php');

  $uploadedfile = $_FILES['image'];
  if($uploadedfile['size'] > 0){
        $upload_overrides = array( 'test_form' => false );
        if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
        $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);
      require_once( ABSPATH . 'wp-admin/includes/image.php' );
      $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
      wp_update_attachment_metadata( $attach_id, $attach_data );

          die(json_encode(array('type'=>'error', 'text' => 'Ok', 'error' => 0)));
        }else{
            die(json_encode(array('type'=>'error',  'error' => 1)));
        }
  }
    die(json_encode(array('type'=>'error', 'error' => 2)));
}
?>

请注意我已经粘贴了我的代码,你必须稍微处理一下;)