I have a Json data and I want to retrieve the image Url and download it in my Local WordPress. Each remote url has its local correspondent. When I want to edit the page in Gutenberg, it displays the image, but I cannot edit / crop the image, it is like it is not downloaded in my local. How can I fix it ?
"__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 -->nn<!-- 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 -->nn<!-- 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 -->nn<!-- 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 -->nn<!-- 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 -->nn<!-- wp:paragraph -->n<p><strong>Pour vous :</strong> Recevez un diagnostic précis et un devis transparent du service dépannage.</p>n<!-- /wp:paragraph -->nn<!-- 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 -->nn<!-- 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 -->nn<!-- 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"
]
}
And my php file to create a post
* 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;
}
} ```