从Url Json中检索古腾堡中的图像

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

我有一个 Json 数据,我想检索图像 Url 并将其下载到我的本地 Wordpress 中。每个远程 URL 都有其本地对应者。当我想在古腾堡中编辑页面时,它会显示图像,但我无法编辑/裁剪图像,就像它没有下载到我的本地一样。我该如何解决它?

    "__file": "wp_block",
    "title": "wooster json",
    "content": "<!-- wp:group {\"layout\":{\"type\":\"constrained\"}} -->\n<div class=\"wp-block-group\"><!-- wp:heading -->\n<h2 class=\"wp-block-heading\">Flexibilité d'Intervention</h2>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p><strong>Pour votre client :</strong> Une transparence qui renforce la confiance et favorise une relation à long terme.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image {\"id\":10342,\"sizeSlug\":\"full\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-full\"><img src=\"https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_standardise_1_3x.webp?fit=550,367\" alt=\"\" class=\"wp-image-10342\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:paragraph -->\n<p><strong>Pour vous : </strong>Des ingénieurs en WordPress à votre service pour résoudre des problèmes spécifiques.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:paragraph -->\n<p><strong>Pour votre client : </strong>Rassurez vos clients en leur montrant que même les problèmes les plus techniques sont résolus de manière professionnelle.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns -->\n\n<!-- wp:paragraph -->\n<p><strong>Pour vous :</strong>&nbsp;Recevez un diagnostic précis et un devis transparent du service dépannage.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:image {\"align\":\"wide\",\"id\":10338,\"sizeSlug\":\"full\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image alignwide size-full\"><img src=\"https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_depannage_1_3x.webp?lossy=1&ssl=1&w=550\" alt=\"\" class=\"wp-image-10338\"/></figure>\n<!-- /wp:image -->\n\n<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column {\"width\":\"66.66%\"} -->\n<div class=\"wp-block-column\" style=\"flex-basis:66.66%\"><!-- wp:paragraph -->\n<p>Wooster est l’équipe technique en coulisses pour chaque prestataires professionnels WordPress. Essentielle et dévouée aux <strong>indépendants</strong> et <strong>agences</strong> qui excellent à renforcer leurs liens clients pendant que nous assurons le volet technique. Ensemble, nous faisons triompher chaque projet.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column -->\n\n<!-- wp:column {\"width\":\"33.33%\"} -->\n<div class=\"wp-block-column\" style=\"flex-basis:33.33%\"><!-- wp:image {\"id\":10328,\"width\":\"209px\",\"height\":\"auto\",\"sizeSlug\":\"full\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-full is-resized\"><img src=\"https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_depannage_3_3x.webp?lossy=1&ssl=1&w=550\" alt=\"\" class=\"wp-image-10328\" style=\"width:209px;height:auto\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns --></div>\n<!-- /wp:group -->",
    "syncStatus": "",
    "img_url": [
        "https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_standardise_1_3x.webp?fit=550,367",
        "https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_depannage_1_3x.webp?lossy=1&ssl=1&w=550",
        "https://cdn-img.wooster.fr/app/uploads/2023/09/wooster_depannage_3_3x.webp?lossy=1&ssl=1&w=550"
    ]
}

我的 php 文件用于创建帖子

     * Create a new post with the content from the JSON file.
     *
     * @return void
     */
    public function create_post()
    {
        if (isset($_POST['submit-gutenberg']) && $_POST['submit-gutenberg'] === 'gutenberg') {
            // Read the JSON file
            $json_data = file_get_contents(__DIR__ . '/partner.json');

            // Check if the JSON file was read successfully
            if ($json_data === false) {
                echo "Erreur de lecture du fichier JSON.";
                return;
            }

            // Decode the JSON data
            $block_data = json_decode($json_data, true);

            // Check if the JSON data was decoded successfully
            if ($block_data === null) {
                echo "Erreur lors du décodage du fichier JSON.";
                return;
            }

            // Retrieve the title, content, and sync status from the JSON data
            $title = isset($block_data['title']) ? $block_data['title'] : '';
            $content = isset($block_data['content']) ? $block_data['content'] : '';
            $sync_status = isset($block_data['syncStatus']) ? $block_data['syncStatus'] : 'draft';
            // Retrieve the image URL from the JSON data
            $img_url = isset($block_data['img_url']) ? $block_data['img_url'] : array();

            // Create a new post page
            $post_data = array(
                'post_title' => $title,
                'post_content' => $content,
                'post_status' => $sync_status,
                'post_type' => 'page',
                'img_url' => $img_url
            );

            // Insert the post into the database
            $post_id = wp_insert_post($post_data);

            // Check if post insertion was successful
            if (is_wp_error($post_id)) {
                echo "Error creating post: " . $post_id->get_error_message();
                 return;
             }

            foreach ($img_url as $image_url) {
                // Download the image and get the attachment ID in the Local WordPress
                $attachment_id = $this->download_image($image_url, $post_id);

                if (!is_wp_error($attachment_id)) {
                    // Get the new local URL of the image
                    $new_url = wp_get_attachment_url($attachment_id);

                    // Replace the old URL with the new URL in the content
                    $content = str_replace($image_url, $new_url, $content);

                    // Update the post content
                    wp_update_post(array(
                        'ID' => $post_id,
                        'post_content' => $content,
                        'img_url' => $new_url
                    ));
                } else {
                    echo "Error downloading image: " . $attachment_id->get_error_message();
                }
            }

            // Get the edit post link after submitting the form
            $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 {
                echo "La création du post a échoué.";
                exit();
            }
        }
    }
    /**
     * Download an image from a URL and attach it to a post.
     *
     * @param string $image_url The URL of the image to download.
     * @param int $post_id The ID of the post to attach the image to.
     * @return int|WP_Error The attachment ID if successful, or a WP_Error object on failure.
     */
    public function download_image($image_url, $post_id)
    {
        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 has already been attached to the post
        $attachment_id = $this->get_attachment_id_by_url($image_url);
        if ($attachment_id) {
            return $attachment_id;
        }
        // Delete the query string from the image URL
        $image_url = strtok($image_url, '?');
        // Download the image and attach it to the post
        $file = media_sideload_image($image_url, $post_id);
        // Retrieve the attachment ID from the file URL
        $attachment_id = $this->get_attachment_id_by_url($file);

        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;
    }
    /**
     * Get the attachment ID of an image by its URL.
     *
     * @param string $url The URL of the image.
     * @return int|false The attachment ID if found, or false if not found.
     */
    public function get_attachment_id_by_url($url)
    {
        // Query to retrieve the attachment ID by the image URL
        global $wpdb;
        $attachment = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid = %s", $url));
        return $attachment ? (int) $attachment : false;
    }
} ```

json wordpress wordpress-gutenberg image-upload imageurl
1个回答
0
投票

要从 JSON URL 检索图像并将其下载到本地 WordPress,您需要:

-从 JSON 数据中提取图像 URL。 - 使用提取的内容创建 WordPress 帖子。 -下载每张图片并将其附加到帖子中。

/**
 * Function to create a post with content from JSON and download images.
 */
function create_post_with_images_from_json() {
    // Read the JSON file
    $json_data = file_get_contents(__DIR__ . '/partner.json');

    // Check if the JSON file was read successfully
    if ($json_data === false) {
        echo "Error reading JSON file.";
        return;
    }

    // Decode the JSON data
    $block_data = json_decode($json_data, true);

    // Check if the JSON data was decoded successfully
    if ($block_data === null) {
        echo "Error decoding JSON data.";
        return;
    }

    // Retrieve the title, content, and sync status from the JSON data
    $title = isset($block_data['title']) ? $block_data['title'] : '';
    $content = isset($block_data['content']) ? $block_data['content'] : '';
    $sync_status = isset($block_data['syncStatus']) ? $block_data['syncStatus'] : 'draft';
    // Retrieve the image URL from the JSON data
    $img_url = isset($block_data['img_url']) ? $block_data['img_url'] : array();

    // Create a new post
    $post_data = array(
        'post_title'   => $title,
        'post_content' => $content,
        'post_status'  => $sync_status,
        'post_type'    => 'page'
    );

    // Insert the post into the database
    $post_id = wp_insert_post($post_data);

    // Check if post insertion was successful
    if (is_wp_error($post_id)) {
        echo "Error creating post: " . $post_id->get_error_message();
        return;
    }

    foreach ($img_url as $image_url) {
        // Download the image and attach it to the post
        $attachment_id = download_and_attach_image($image_url, $post_id);

        if (is_wp_error($attachment_id)) {
            echo "Error downloading image: " . $attachment_id->get_error_message();
        }
    }

    // Redirect to the edit post page
    wp_redirect(admin_url("post.php?post=$post_id&action=edit"));
    exit();
}

/**
 * Function to download an image and attach it to a post.
 */
function download_and_attach_image($image_url, $post_id) {
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    // Download the image
    $image = media_sideload_image($image_url, $post_id);

    // Check if image download was successful
    if (is_wp_error($image)) {
        return $image;
    }

    // Get the attachment ID of the downloaded image
    $attachment_id = attachment_url_to_postid($image);

    // Attach the image to the post
    if ($attachment_id && !is_wp_error($attachment_id)) {
        set_post_thumbnail($post_id, $attachment_id);
    }

    return $attachment_id;
}

您可以调用

create_post_with_images_from_json()
函数使用 JSON 文件中的内容创建新帖子并下载关联的图像。确保根据您的设置需要调整文件路径和 URL。

© www.soinside.com 2019 - 2024. All rights reserved.