Posted in WordPress

WordPress Code Snippets 2

  • Upload and insert some attachments.
  • How get attachment id from guid?


Upload and insert some attachments.

$dummy = array(
	'attachments' => array(
		array(
			'title' => 'Image 1',
			'content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
			'url' => 'http://some_url/image.jpg',
		),	
		array(
			'title' => 'Image 2',
			'content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
			'url' => 'http://some_url/image_2.jpg',
		),				
	)
);

$attachments_ids = array();
foreach ($dummy['attachments'] as $image) {
	$photo = new WP_Http();
	$photo = $photo->request( $image['url'] );
	$attachment = wp_upload_bits( $image['url'], null, $photo['body'], date("Y-m", strtotime( $photo['headers']['last-modified'] ) ) );
	$filetype = wp_check_filetype( basename( $attachment['file'] ), null );
	$args = array(
		'post_mime_type' => $filetype['type'],
		'post_title'	 => $image['title'],
		'post_content'	 => $image['content'],
		'post_status'	 => 'inherit',
	);
	$filename = $attachment['file'];
	$attach_id = wp_insert_attachment( $args, $filename, $postid );
	$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
	wp_update_attachment_metadata( $attach_id,  $attach_data );

	$attachments_ids[] = $attach_id;
}

How get attachment id from guid?

function get_attachment_id_from_guid( $guid ) {
	global $wpdb;

	if ( ! $guid ) {
		return false;
	}

	// Get the ID
	$id = $wpdb->get_var( $wpdb->prepare("
		SELECT p.ID 
		FROM $wpdb->posts p
		WHERE p.guid = %s 
			AND p.post_type = %s",
		$guid,
		'attachment'
	) );

	// ID not found, try getting it the expensive WordPress way
	if ( $id == 0 ) {
		$id = url_to_postid( $guid );
	}

	return $id;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s