Я пытался загрузить изображение и вставить носитель в библиотеку. Когда я использую свой URL-адрес в данных json: «my_site_url/wp-content/uploads/2024/04/wooster_sur-mesure_1_3x-1-4545.webp\\», это работает, но Я хочу отобразить происхождение URL-адреса:
$image_url = '
';URL-адрес неизвестен.
* 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 = '
';//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": "\\n
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.
\\n\\n\\n\\n
\\n",
"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();
}}`
Подробнее здесь: https://stackoverflow.com/questions/783 ... -wordpress
Мобильная версия