Import Flickr Shortcode 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 Shortcode Into WordPress Media Library Programmatically

We’ve recently taken on a project at Bold City Design where we needed to export a large site from Joomla and import it into WordPress so I will be sharing some odds and ends on the project as we go through it.

One major point of contention was their media which was nearly 100% stored with Flickr and accessed via shortcodes.  As part of the transfer and re-development of this site, they wanted to import the photos into the natural WordPress media library.  After hitting the Google search queries, I did stumble across a plugin that showed some promise, https://wordpress.org/plugins/flickr-shortcode-importer/.  However, after some testing and below average results (I couldn’t even get this to work with custom post types?), I came to the conclusion that a custom plugin was going to be the way to go.

As mentioned, we had exported the posts from Joomla and were importing them into WordPress.  To make the process a little bit easier, we assigned the featured image Flickr shortcode to it’s own custom field during import.  So basically I had a bunch of posts in WordPress that had a custom field name of ‘flickr_featured_photo’ and a value that looked something like: ‘[flickr id=89236532753275]’.

Once my data was in place, I was ready to start developing the plugin.  To start, let’s get the basic plugin info added:

 

<?php
/**
* Plugin Name: Flickr 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, I’m going to add in my form processing (what happens after clicking the ‘Go’ button):

<?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_featured_photo')) {
			
			$pieces = explode("=", get_field('flickr_featured_photo'));
			$photoid = substr(preg_replace('/\s+/', '', $pieces[1]), 0, -1);
			$api_key = 'yourapikey';
			 
			$url = 'https://api.flickr.com/services/rest/?method=flickr.photos.getSizes';
			$url.= '&api_key='.$api_key;
			$url.= '&photo_id='.$photoid;
			$url.= '&format=json&nojsoncallback=1';
			 
			$response = json_decode(file_get_contents($url));
			$photo_array = $response->sizes->size;
			if(!empty($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);
						$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 );
						
						
						if(!empty($attach_id)) {
							update_field('featured_photo', $attach_id, $parent_post_id);
							echo $ogphoto . '<br />';
							update_field('flickr_featured_photo', '', $parent_post_id);
						} else {
							echo $parent_post_id . ' Has Failed For Featured Image.<br />';
						}
					}
				}
				
			}
		}
		endwhile; 
		endif; wp_reset_query();
	}
?>

The above query is checking to see if the custom field ‘flickr_featured_photo’ is not empty within the post. If so, we are getting the Flickr image ID from the shortcode by exploding the string at the equal sign. We are then generating a URL to fetch the image from Flickr. For this example, I want to see if a Large 1600 image size exists within the fetched image, if so I want to grab it. As a second choice I’m looking just for a Large image, and as a fallback we’ll just grab the Original if neither options exist. As a side note, make sure you update the Flickr API key with your specific key. This can be found within your Flickr account.

Once we have the image, we’re assigning it the filename of the post for better SEO practice but appending some numbers to keep all filenames unique. Next, we are inserting the image data into the WordPress media library. Finally, if everything goes as planned, we are updating another ACF custom field named ‘featured_photo’ with the attachment ID and also removing the value from the field ‘flickr_featured_photo’ to signify that this post has been complete. Doing this last step solves any issues with server timeouts as you can always restart the process and it will leave off where it left off.

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 } ?>

Thanks for following along, hopefully this assists with other migrations from Flickr to WordPress media library. In part two of this series coming out next week, we’ll also learn how to deal with Flickr Photosets and import them into an Advanced Custom Fields gallery custom field. Stay Tuned!


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!