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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?