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 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle