如何在 WordPress 中的帖子中显示 URL 中的图像?

问题描述 投票:0回答:1

我正在尝试创建一个页面,以便在古腾堡中使用文本和图像进行编辑。图像必须在媒体中下载(从网址)并显示在我生成的页面中。

我尝试下载图像并将媒体插入库中。当我在 json 数据中使用我的 url 时:

"my_site_url/wp-content/uploads/2024/04/wooster_sur-mesure_1_3x-1-4545.webp\\
",它有效,但我想显示 URL 来源:
$image_url = 'https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_sur-mesure_1_3x-1.webp?lossy=1&ssl=1&w=500';

网址未知。

     * Function to download image from URL
     *  @param string $image_url The URL of the image to download
    * @param string $image_alt The alt text for the image
     */
    public function download_image($image_url)
    {
        $image_url = 'https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_sur-mesure_1_3x-1.webp?lossy=1&ssl=1&w=500';
        //Download the image if it doesn't already exist
        $attachment_id = $this->get_attachment_id_by_url($image_url);
        if ($attachment_id) {
            // If the image already exists, return his id
            return $attachment_id;
        }
        // It downloads the image from the URL
        $image = media_sideload_image($image_url);
        return $image;
    }
    /***
     * To insert the media in library and get the attachment id
     *
     */
    public function insert_to_media($image_url)
    {
        //Put the downloaded image into the variable $image
        $image = $this->download_image($image_url);

        // Then insert the $image into the media library
        $attachment = wp_insert_attachment(array(
            'post_title' => 'Image Wooster téléchargée',
            'post_content' => 'Image wooster',
            'post_status' => 'draft',
        ), $image);

        // Generate metadata for the image
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attachment, $image);
        wp_update_attachment_metadata($attachment, $attach_data);

        return $attachment;
    }

    /***
     * Function to get attachment ID by URL with a personalized query
     * @param $image_url
     */
    public function get_attachment_id_by_url($image_url)
    {
        global $wpdb;
        $attachment_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s'", $image_url));
        return $attachment_id;
    }
    /**
     * Function to create a post with the content of the JSON data
     *
     * @return void
     */
    public function create_post()
    {
        // Check if the form has been submitted
        if (isset($_POST['submit-gutenberg']) && $_POST['submit-gutenberg'] === 'gutenberg') {
            // Retrieve the JSON data
            $json_data = '{
                "__file": "wp_block",
                "title": "Partenariat Wooster",
                "content": "<!-- wp:paragraph -->\\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget vehicula orci, ut iaculis ex. Donec sed ornare nisi. Donec non sollicitudin ex. Aliquam at leo non odio hendrerit consectetur. Sed porttitor lacus placerat metus viverra facilisis. Aenean gravida ornare purus, ut posuere lectus dictum a. Nunc nisi leo, porta ut porta et, porttitor quis ante. In id arcu in sem vulputate fermentum. Vivamus libero augue, finibus id eros in, gravida vestibulum ex. Quisque ultrices, odio et consectetur vestibulum, arcu mi elementum nulla, a elementum massa libero quis nibh. Aenean pulvinar diam sem, a auctor nisl ullamcorper at.</p>\\n<!-- /wp:paragraph -->\\n\\n<!-- wp:image {\\"id\\":10217,\\"sizeSlug\\":\\"full\\",\\"linkDestination\\":\\"none\\"} -->\\n<figure class=\\"wp-block-image size-full\\"><img src=\\"my_site_url/wp-content/uploads/2024/04/wooster_sur-mesure_1_3x-1-4545.webp\\" alt=\\"\\" class=\\"wp-image-10217\\"/></figure>\\n<!-- /wp:image -->",
                "syncStatus": "draft"

            }';

            // Decode the JSON data
            $data = json_decode($json_data, true);
            $data['content'] = str_replace('my_site_url', esc_url( home_url() ), $data['content']);

            // Extraire l'URL de l'image
            preg_match('/src="([^"]+)"/', $data['content'], $matches);
            $image_url = $matches[1];

            // Download the image from the URL to the media library
            media_sideload_image($image_url, 'Image téléchargée depuis l\'URL');

            // Create the post content Gutenberg block
            $post_content = $data['content'];


            // Data for the post
            $post_data = array(
                'post_type' => 'page',
                'post_status' => 'draft',
                'post_title' => $data['title'],
                'post_content' => $post_content,
            );

            // Insert those data by creating a post page
            $post_id = wp_insert_post($post_data);

            // Check if the post has been created
            if ($post_id) {
                // Get the edit post link
                $edit_post_link = admin_url("post.php?post=$post_id&action=edit");

                if ($edit_post_link) {
                    // Redirect to the edit post page
                    wp_redirect($edit_post_link);
                    exit();
                }
            } else {
                // Check if the post creation failed
                echo "La création du post a échoué.";
                exit();
            }}`
json wordpress media wordpress-gutenberg wp-insert-post
1个回答
0
投票

以下是您的代码中遇到的一些问题

  1. media_sideload_image
    不返回下载图片的路径;它会在失败时返回 HTML 代码或 WP_Error。你需要妥善处理这个问题。
  2. wp_insert_attachment
    需要文件路径才能将图像正确插入媒体库,而不是 HTML 字符串。
  3. 图像 URL 在使用之前需要进行处理和操作,因为可能的查询字符串不属于实际文件名的一部分。

我稍微修正了你的代码

class YourClass {
  /**
   * Function to download an image from a URL and add it to the media library
   * @param string $image_url URL of the image
   * @return int|WP_Error The attachment ID on success, WP_Error on failure
   */
  public function download_image($image_url) {
      require_once(ABSPATH . 'wp-admin/includes/media.php');
      require_once(ABSPATH . 'wp-admin/includes/file.php');
      require_once(ABSPATH . 'wp-admin/includes/image.php');
  
      // Check if the image already exists
      $attachment_id = $this->get_attachment_id_by_url($image_url);
      if ($attachment_id) {
          return $attachment_id;
      }
  
      // Remove any query strings from the URL
      $image_url = strtok($image_url, '?');
      // Sideload image returns an HTML img tag on success
      $file = media_sideload_image($image_url, 0, null, 'src');
      if (is_wp_error($file)) {
          return $file; // Return the error if media_sideload_image failed
      }
  
      $attachment_id = $this->get_attachment_id_by_url($file); // Get the ID of the newly added image
      if (!$attachment_id) {
          return new WP_Error('failed_to_retrieve_attachment', "Échec de l'extraction de l'ID de la pièce jointe.");
      }
  
      return $attachment_id;
  }
  
  /**
   * Helper function to get an attachment ID given a URL
   * @param string $url
   * @return int|bool The attachment ID or false if not found
   */
  public function get_attachment_id_by_url($url) {
      global $wpdb;
      $attachment = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid = %s", $url));
      return $attachment ? (int) $attachment : false;
  }
  
  /**
   * Function to create a Gutenberg post with a specific image and text
   */
  public function create_post() {
      $image_url = 'https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_sur-mesure_1_3x-1.webp';
      $attachment_id = $this->download_image($image_url);
  
      if (is_wp_error($attachment_id)) {
          echo "Erreur de téléchargement de l'image : " . $attachment_id->get_error_message();
          return;
      }
  
      $image_html = wp_get_attachment_image($attachment_id, 'full');
  
      // Construct post content with proper Gutenberg block structure
      $post_content = <<<HTML
      <!-- wp:paragraph -->
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
      <!-- /wp:paragraph -->
  
      <!-- wp:image {"id":{$attachment_id},"sizeSlug":"full"} -->
      <figure class="wp-block-image size-full">{$image_html}</figure>
      <!-- /wp:image -->
      HTML;
  
      $post_data = [
          'post_type'    => 'page',
          'post_status'  => 'draft',
          'post_title'   => 'Partenariat Wooster',
          'post_content' => $post_content,
      ];
  
      $post_id = wp_insert_post($post_data);
  
      if ($post_id) {
          echo "Post créé avec succès! Editer <a href='" . admin_url("post.php?post=$post_id&action=edit") . "'>ici</a>.";
      } else {
          echo "La création du post a échoué";
      }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.