Skip to content

Instantly share code, notes, and snippets.

@guytzhak
Created May 15, 2021 12:07
Show Gist options
  • Save guytzhak/d6db193a286f441925c575c55861459e to your computer and use it in GitHub Desktop.
Save guytzhak/d6db193a286f441925c575c55861459e to your computer and use it in GitHub Desktop.
getImage
public static function getImage( $pic, $parent_id = '', $filename = false ) {
$server = WC_LI_Settings::SERVER;
$dev = get_option( 'wc_linet_dev' );
if ( $dev == 'on' ) {
$server = WC_LI_Settings::DEV_SERVER;
}
$basePath = wp_upload_dir()['basedir'] . '/';
if( $filename ) {
$realtivePath = self::IMAGE_DIR . "/" . $filename;
} else {
$realtivePath = self::IMAGE_DIR . "/" . $pic;
}
$filePath = $basePath . $realtivePath;
if ( ! is_dir( $basePath ) ) {
mkdir( $basePath );
}
if ( ! is_dir( $basePath . self::IMAGE_DIR ) ) {
mkdir( $basePath . self::IMAGE_DIR );
}
if ( $pic != '' ) {
if ( ! is_file( $filePath ) || filesize( $filePath ) == 0 ) {
$ch = curl_init();
curl_setopt_array( $ch, array(
CURLOPT_URL => $server . "/site/largethumbnail/" . $pic,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: application/json' ),
) );
$response = curl_exec( $ch );
$content_type = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
$content_type = explode( "; ", $content_type );
if (
! isset( $content_type[0] ) ||
( substr( $content_type[0], 0, 6 ) !== "image/" )
) {
return false;
}
$ext = substr( $content_type[0], 6 );
if( isset($ext) && !empty($ext) ) {
$filePath .= '.'. $ext;
if( !$filename ) {
$realtivePath .= '.'. $ext;
}
}
file_put_contents( $filePath, $response );
}
global $wpdb;
$query = "SELECT ID FROM $wpdb->posts WHERE post_name = '%s' AND post_type = 'attachment' LIMIT 1";
$image_id = $wpdb->get_col( $wpdb->prepare( $query, $pic ) );
if ( count( $image_id ) == 0 ) {
$attachment = array(
'post_mime_type' => mime_content_type( $filePath ),
'post_title' => sanitize_file_name( $pic ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filePath );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filePath );
wp_update_attachment_metadata( $attach_id, $attach_data );
} else {
$post_id = $image_id[0];
}
//* //save new post
return $post_id;//*/
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment