douxugu5836 2019-02-27 11:34
浏览 40
已采纳

以编程方式将图像上载到Wordpress

I'm trying to programmatically upload images to the media library by taking an ACF url, running it through the Wordpress function and then updating a taxonomy field.

I know for a fact that $icon is the correct URL and the update_field function is correct.

The part that is going wrong is the upload image part. I think I've followed the documentation correctly but no image is uploaded into the library and nothing is connected to the ACF field on the taxonomy.

Where am I going wrong?

    // Icon
    $icon = get_field('icon', $term->taxonomy . '_' . $term->term_id);
    $field_key = "field_5ad5e7e5e295c";

    if($icon != "") {
      // The ID of the post this attachment is for.
      $return = "id";

      // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
      require_once(ABSPATH . 'wp-admin/includes/media.php');
      require_once(ABSPATH . 'wp-admin/includes/file.php');
      require_once(ABSPATH . 'wp-admin/includes/image.php');

      // Generate the metadata for the attachment, and update the database record.
      $attach_id = media_sideload_image($icon, $post_id, $desc, id);


      update_field( $field_key, $attach_id, $taxonomy.'_'.$french );
      update_field( $field_key, $attach_id, $taxonomy.'_'.$german );
      update_field( $field_key, $attach_id, $taxonomy.'_'.$italian );
      update_field( $field_key, $attach_id, $taxonomy.'_'.$russian );
      update_field( $field_key, $attach_id, $taxonomy.'_'.$spanish );
    }
  • 写回答

1条回答 默认 最新

  • dou7851 2019-02-27 13:49
    关注

    I've actually found a really simple way around... it doesn't solve my question as such as I've approached it a different way.

    The url of the media item obviously already exists in the media library. Therefore I just need the item id of it by looking via the url.

        // Icon
        $icon = get_field('icon', $term->taxonomy . '_' . $term->term_id);
        $field_key = "field_5ad5e7e5e295c";
    
        if($icon != "") {
    
          $item = attachment_url_to_postid( $icon );
    
          update_field( $field_key, $item, $taxonomy.'_'.$french );
          update_field( $field_key, $item, $taxonomy.'_'.$german );
          update_field( $field_key, $item, $taxonomy.'_'.$italian );
          update_field( $field_key, $item, $taxonomy.'_'.$russian );
          update_field( $field_key, $item, $taxonomy.'_'.$spanish );
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同