Skip to content

Instantly share code, notes, and snippets.

@tpitre
Last active September 23, 2020 20:23
Show Gist options
  • Save tpitre/996bafa43abbb5abb9e28b0eb53baab5 to your computer and use it in GitHub Desktop.
Save tpitre/996bafa43abbb5abb9e28b0eb53baab5 to your computer and use it in GitHub Desktop.
WP image fetching and attaching to post
function process_image() {
$response = '';
$data[] = '';
$error = 0;
if ( isset( $_POST['ids'] ) )
$ids = $_POST['ids'];
$data['choose-tool'] = $_POST['args'];
$post = get_post( $ids );
$response .= '<h3><a href="' . esc_url( admin_url( 'post.php?post=' . $post->ID . '&action=edit' ) ) . '" target="_blank">'.get_the_title( $post->ID ) . '</a></h3>';
if ( 'import-media' == $data['choose-tool'] ) {
$response .= 'Running import media tool<br>';
$res = $this->extract_multi( $post );
$response .= $res['response'];
$error = $error + (int)$res['error'];
die( sprintf( $response . '<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
} elseif ( 'convert-import' == $data['choose-tool'] ) {
$response .= 'Running import and set featured image tool<br>';
$res = $this->extract_multi( $post );
$response .= $res['response'];
$error = $error + (int)$res['error'];
}
/** If the post already has an attached thumbnail continue with the loop */
if ( has_post_thumbnail( $post->ID ) ) {
$response .= 'Featured image already set <br>';
die( sprintf( $response . '<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
}
/** @var $attachments array of attached images to the post */
$attachments = $this->get_attach( $post->ID );
if ( ! $attachments ) {
$img = $this->extract_image( $post );
if( empty( $img ) ) {
$response .= 'No images found <br>';
die( sprintf( $response . '<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
}
/** @var $file string or WP_Error of image attached to the post */
$file = media_sideload_image( $img, (int)$post->ID );
if ( is_wp_error( $file ) ) {
$response .= '<span style="color:red">Upload Error: Could not upload image. Check for malformed img src url</span><br>';
$error++;
} else {
$atts = $this->get_attach( $post->ID );
foreach ( $atts as $a ) {
$img = set_post_thumbnail( $post->ID, $a['ID'] );
if ( $img ) {
$thumb = wp_get_attachment_thumb_url( $a['ID'] );
$response .= '<img src="'.esc_url( $thumb ).'" /><br>';
$response .= '<a href="' . wp_nonce_url( get_edit_post_link( $a['ID'], true ) ) . '" >' . get_the_title( $a['ID'] ) . '</a> Set as Featured Image</p><br>';
}
}
unset( $atts );
unset( $a );
}
} else {
foreach( $attachments as $a ) {
$img = set_post_thumbnail( $post->ID, $a['ID'] );
if ( $img ) {
$thumb = wp_get_attachment_thumb_url( $a['ID'] );
$response .= '<img src="' . esc_url( $thumb ) . '" /><br>';
$response .= '<a href="' . wp_nonce_url( get_edit_post_link( $a['ID'], true ) ) . '" >' . get_the_title( $a['ID'] ) . '</a> Set as Featured Image</p><br>';
}
}
unset( $attachments );
unset( $a );
}
die( sprintf( $response.'<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
}
/**
* Queries for attached images
* @param int $post_id The post id to check if attachments exist
* @return array|bool The 1st attached on success false if no attachments
*/
function get_attach( $post_id ) {
return get_children( array (
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => (int)1
), ARRAY_A );
}
/**
* Extracts the first image in the post content
* @param object $post the post object
* @return bool|string false if no images or img src
*/
function extract_image( $post ) {
$html = $post->post_content;
if ( stripos( $html, '<img' ) !== false ) {
$regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
preg_match( $regex, $html, $matches );
unset( $regex );
unset( $html );
if ( is_array( $matches ) && ! empty( $matches ) ) {
return $matches[2];
} else {
return false;
}
} else {
return false;
}
}
/**
* Extracts all images in content adds to media library if external and updates content with new url
* @param object $post The post object
* @return array|bool Post id and images converted on success false if no images found in source
*/
function extract_multi( $post ) {
$html = $post->post_content;
$path = wp_upload_dir();
$path = $path['baseurl'];
$error = 0;
$response = '';
if ( stripos( $html, '<img' ) !== false ) {
$regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
preg_match_all( $regex, $html, $matches );
if ( is_array( $matches ) && ! empty( $matches ) ) {
$new = array();
$old = array();
foreach( $matches[2] as $img ) {
/** Compare image source against upload directory to prevent adding same attachment multiple times */
if ( stripos( $img, $path ) !== false ) {
$response .= 'Img already in media library<br>';
continue;
}
$tmp = download_url( $img );
preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $img, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
continue;
}
$id = media_handle_sideload( $file_array, $post->ID );
if ( ! is_wp_error( $id ) ) {
$url = wp_get_attachment_url( $id );
$thumb = wp_get_attachment_thumb_url( $id );
array_push( $new, $url );
array_push( $old, $img );
$response .= '<p><a href="'. wp_nonce_url( get_edit_post_link( $id, true ) ).'" title="edit-image"><img src="'.esc_url( $thumb ).'" style="max-width:100px;" /></a><br>';
$response .= '<a href="'. wp_nonce_url( get_edit_post_link( $id, true ) ).'" >'.get_the_title( $id ). '</a> Imported and attached</p>';
} else {
$response .= '<span style="color:red">Upload Error: Could not upload image. Check for malformed img src url</span><br>';
$error ++;
}
}
if( !empty( $new ) ) {
$content = str_ireplace( $old, $new, $html );
$post_args = array( 'ID' => $post->ID, 'post_content' => $content, );
if ( !empty( $content ) )
$post_id = wp_update_post( $post_args );
if ( isset( $post_id ) )
$response .= 'Post Content updated for Post: '.esc_html( $post->post_title).'<br>';
return array( 'error' => $error, 'response' => $response );
} else
$response .= 'No external images found for ' . esc_html( $post->post_title ) . '<br>';
return array ( 'error' => $error, 'response' => $response );
} else {
$response .= 'Error processing images for '. esc_html( $post->post_title ) .'<br>';
return array ( 'error' => $error, 'response' => $response );
}
} else {
$response .= 'No images found for ' . esc_html( $post->post_title) . '<br>';
return array ( 'error' => $error, 'response' => $response );
}
}
/**
* Queries the posts based on the form field data
* The database MySql queries were <del>inspired</del> jacked from the WordPress Export tool
*
* @param array $args The ajax form array formatted for the query
* @return array $post_ids an array of post ids from the query result
*/
function query( $args = array() ) {
global $wpdb, $post;
$defaults = array( 'content' => 'all', 'author' => false, 'category' => false,
'start_date' => false, 'end_date' => false, 'status' => false, );
$args = wp_parse_args( $args, $defaults );
if ( 'all' != $args['content'] && post_type_exists( $args['content'] ) ) {
$ptype = get_post_type_object( $args['content'] );
if ( ! $ptype->can_export )
$args['content'] = 'post';
$where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['content'] );
} else {
$post_types = get_post_types();
$post_types = array_diff( $post_types, array( 'attachment', 'revision', 'nav_menu_item' ) );
$esses = array_fill( 0, count($post_types), '%s' );
$where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types );
}
if ( $args['status'] && ( 'post' == $args['content'] || 'page' == $args['content'] ) )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] );
else
$where .= " AND {$wpdb->posts}.post_status != 'auto-draft'";
$join = '';
if ( $args['category'] && 'post' == $args['content'] ) {
if ( $term = term_exists( $args['category'], 'category' ) ) {
$join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] );
}
}
if ( 'post' == $args['content'] || 'page' == $args['content'] ) {
if ( $args['author'] )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $args['author'] );
if ( $args['start_date'] )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", date( 'Y-m-d', strtotime($args['start_date']) ) );
if ( $args['end_date'] )
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", date( 'Y-m-d', strtotime('+1 month', strtotime($args['end_date'])) ) );
}
$post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where ORDER BY ID ASC" );
return $post_ids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment