Import Flickr Gallery Into WordPress Media Library Programmatically


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Import Flickr Gallery Into WordPress Media Library Programmatically

Last week I outlined the process for importing a single Flickr image shortcode into the WordPress media library programmatically. If you haven’t checked it out, give it a read first as it is a segue into this part two post.

Today, we’re going to look at how to complete the same task except with a Flickr Gallery, importing each image individually to the media library and then saving the media IDs to an Advanced Custom Fields gallery field.

Let’s jump right in. As mentioned, the base of the plugin will be pulled from our previous post so let’s start out with creating our basic plugin:

 

<?php
/**
* Plugin Name: Flickr Gallery Import - Custom
* Plugin URI: https://www.wpcover.com
* Description: Flickr Import Into WordPress
* Version: 1.0
* Author: Cabe Nolan
* Author URI: https://www.boldcitydesign.com
* License: GPL12
*/

/*---------------------------------------------------
add settings page to menu
----------------------------------------------------*/
function add_flickr_import_page() {
add_submenu_page( 'tools.php', 'Import Flickr Custom', 'Import Flickr Custom', 'manage_options', 'import-flickr', 'import_flickr' );
}
add_action( 'admin_menu', 'add_flickr_import_page' );

function import_flickr() {
?>

<div class="wrap import-csv">
	<h2>Import Flickr</h2>
	<p>Click Process button to run through posts and import data.</p>

Next, we’ll handle the processing of the Flickr gallery once the submit button has been clicked.

<?php
//some security checks
	if ( isset( $_POST['_wpnonce-is-iu-import-users-users-page_import_cn'] ) ) {
	check_admin_referer( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' );
	// setup our query args
	$args = array(
		'posts_per_page'	=> -1,
		'post_type'		=> 'post',
	);
	
	$the_query = new WP_Query( $args );
	if( $the_query->have_posts() ):
		while( $the_query->have_posts() ) : $the_query->the_post();
		$parent_post_id = get_the_ID();
		if(get_field('flickr_gallery')) { $i++;
			echo $parent_post_id . '<br />';
			$pieces = explode("=", get_field('flickr_gallery'));
			$photoid = substr(preg_replace('/\s+/', '',$pieces[1]), 0, -1);
			$api_key = 'yourapikey';
                        $flickr_userid = 'yourflickruserid';
			 
			$url = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos';
			$url.= '&api_key='.$api_key;
			$url.= '&photoset_id='.$photoid;
			$url.= '&user_id='.$flickr_userid;
			$url.= '&format=json&nojsoncallback=1';
			$response = json_decode(file_get_contents($url));
			$photo_array = $response->photoset->photo;
			//print_r($photo_array);
			$failedgal = array();
			if(!empty($photo_array)) {
				$galleryarray = array();
				foreach($photo_array as $photo) {
					$singlephotoid = $photo->id;
					 
					$url = 'https://api.flickr.com/services/rest/?method=flickr.photos.getSizes';
					$url.= '&api_key='.$api_key;
					$url.= '&photo_id='.$singlephotoid;
					$url.= '&format=json&nojsoncallback=1';
					 
					$response = json_decode(file_get_contents($url));
					$photo_array = $response->sizes->size;
					//print_r($photo_array);
					$photolabels = array();
					foreach($photo_array as $photo) {
						$photolabels[] = $photo->label;	
					}
					if(in_array('Large 1600', $photolabels)) {
						$label = 'Large 1600';
					} elseif(in_array('Large 1600', $photolabels)) {
						$label = 'Large';
					} else {
						$label = 'Original';
					}
					foreach($photo_array as $photo) {
						if($photo->label == $label) {
							$ogphoto = $photo->source;
							
							global $post;
							$filename = $post->post_name . '-' . rand(10000, 999999999) . '.jpg';
							$uploaddir = wp_upload_dir();
							$uploadfile = $uploaddir['path'] . '/' . $filename;
							$contents= file_get_contents($ogphoto);
							if(empty($contents)) { $failedgal[] = $parent_post_id; }
							$savefile = fopen($uploadfile, 'w');
							fwrite($savefile, $contents);
							fclose($savefile);
							
							$wp_filetype = wp_check_filetype(basename($filename), null );
		
							$attachment = array(
							    'post_mime_type' => $wp_filetype['type'],
							    'post_title' => $filename,
							    'post_content' => '',
							    'post_status' => 'inherit'
							);
							
							$attach_id = wp_insert_attachment( $attachment, $uploadfile, $parent_post_id );
							
							// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
							require_once( ABSPATH . 'wp-admin/includes/image.php' );
							
							// Generate the metadata for the attachment, and update the database record.
							$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
							wp_update_attachment_metadata( $attach_id, $attach_data );
							
							$galleryarray[] = $attach_id;
							
							
						}
					}
					
				}
				if(!in_array($parent_post_id, $failedgal)) {
					update_field('flo_gallery', $galleryarray, $parent_post_id);
					update_field('flickr_gallery', '', $parent_post_id);
				} else {
					echo $parent_post_id . ' Has Failed For Gallery Image.<br />';
				}
			}
		}
		endwhile; 
		endif; wp_reset_query();
	}
?>

First and foremost, make sure you swap out the Flickr API Key and the Flickr Username details with your info. The Flickr username is the username of the account for which you will be querying the gallery.

To jump into the functionality, this query is first looking to see if the ACF custom field flickr_gallery is not empty. This flickr_gallery field is where we are storing the shortcode in the format of [flickrset id=89236532753275].

If this custom field is not empty, we are using the Flickr API method called flickr.photosets.getPhotos to create an array of photos assigned to this gallery. Once we have that array set, we’re going to loop through each of those photos using the same flickr.photos.getSize method we used in part one of this tutorial. For each photo we are grabbing the appropriate size, adding it to the WordPress media library, and then adding the attachment ID to an array called $galleryarray.

Once we’ve looped through each photo in the Flickr photoset, we’re going to save the $galleryarray attachment IDs to another ACF custom field titled flo_gallery. Make sense?

As a final addition to the plugin, we need to add in our HTML form and close out the import_flickr() function we started like so:

	<form method="post" action="">
		<?php wp_nonce_field( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' ); ?>
		<p class="submit">
		 	<input type="submit" class="button-primary" value="Process Posts" />
		</p>
	</form>
<?php } ?>

We’ve now covered how to import single images from Flickr into the WordPress media library as well as Flickr Photo Sets (galleries). I hope this will help you take on your next Flickr to WordPress migration task!


Comments:

Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!