Skip to content

Instantly share code, notes, and snippets.

@19h47
Last active April 19, 2023 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 19h47/f85ab2722676b1f8e2f86cb2451792b6 to your computer and use it in GitHub Desktop.
Save 19h47/f85ab2722676b1f8e2f86cb2451792b6 to your computer and use it in GitHub Desktop.
WP Insert Image
<?php
/**
* Plugin Name: WP Insert Image
* Plugin URI: https://gist.github.com/19h47/f85ab2722676b1f8e2f86cb2451792b6
* Description: WordPress insert image.
* Version: 0.0.0
* Author: Jérémy Levron
* Author URI: https://19h47.fr
*/
if ( ! function_exists( 'wp_insert_image' ) ) {
/**
* Insert an image from URL.
*
* @see https://gist.github.com/raazon/a00c6d0c5b3c4b8346ed139d84d923ea
*
* @param string $url
* @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
*
* @return int|WP_Error The ID of the attachment or a WP_Error on failure.
*/
function wp_insert_image( string $url, $post ) {
$post = get_post( $post );
if ( ! function_exists( 'media_handle_upload' ) ) {
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
}
if ( null === $post ) {
return new WP_Error( 'insert_attachment_failed', __( 'Invalid post' ) );
}
if ( empty( $url ) ) {
return new WP_Error( 'insert_attachment_failed', __( 'Insert URL' ) );
}
$url = esc_url( $url );
// Set variables for storage, fix file filename for query strings.
preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches );
if ( ! $matches ) {
return new WP_Error( 'insert_attachment_failed', __( 'Invalid image URL' ) );
}
// Array that represents a `$_FILES` upload array.
$file_array = array();
$file_array['name'] = basename( $matches[0] );
// @see https://developer.wordpress.org/reference/functions/download_url/
$file_array['tmp_name'] = download_url( $url );
if ( is_wp_error( $file_array['tmp_name'] ) ) {
return $file_array['tmp_name'];
}
return media_handle_sideload( $file_array, $post->ID );
// @see https://developer.wordpress.org/reference/functions/media_handle_sideload/
// $attachment_id = media_handle_sideload( $file_array, $post->ID );
// if ( is_wp_error( $attachment_id ) ) {
// return $attachment_id;
// }
// @see https://developer.wordpress.org/reference/functions/set_post_thumbnail/
// $post_thumbnail = set_post_thumbnail( $post->ID, $attachment_id );
// if ( false === $post_thumbnail ) {
// return new WP_Error( 'insert_attachment_failed', __( 'Problem to set post thumbnail' ) );
// }
// return $attachment_id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment