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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题