Instagram photos can serve as a great source of supplemental content on your website. Photos from Instagram are commonly displayed in widget areas, but let’s take a look at creating individual WordPress posts for each photo. This approach will give us the ability to embed those photos within the rest of our content or custom loops and fine-tune the way they are displayed. We will also setup a background task to check for new Instagram photos and import them automatically as they are available.

Here is a quick look at the steps we will take to import our Instagram photos to WordPress:

  1. Set Up Instagram Developer Account
  2. Create a New WordPress Plugin
  3. Get Recent Photos from User Instagram Feed
  4. Import Each Photo as a Single Post
  5. Schedule Event to Check for New Photos

In order to understand this tutorial, you should have a basic knowledge of WordPress development and how third-party APIs work. You will also need to have WordPress installed with the ability to edit files. I will be using the TwentyTwelve theme in my examples, but if you want to use a different theme – go for it!

Set Up Instagram Developer Account

You will need to set up an Instagram developer account before importing photos from Instagram. This account will allow us to make use of the Instagram API, which is how we can control and customize which pictures are used. It is important to note that the developer account is not separate from your Instagram user account, but only a little extra information that lets Instagram know you want to use their API.

After signing up, you will need to register your project/website to generate a Client ID. This identifier will be used to authorize requests within the API framework and return photos that match the search criteria. Instagram requires you to register each project/website as a new client and tracks the number of requests made to prevent overloading the API with too many requests.

Register New Client with Instagram API

Create a New WordPress Plugin

The first thing we need to do is create a new plugin, which is where we will write all of the code for this tutorial. Adding our new features to a plugin, instead of directly to the theme, will allow us to easily deactivate the plugin for troubleshooting.

Add a new folder in the plugins directory called instagram-import. Create a new file in that folder called instagram-import.php and add the following code to it .

<?php
    /*
     *  Plugin Name: Instagram Import
    *   Plugin URI: https://litzdigital.com
    *   Description: Imports Instagram photos as posts to your WordPress site
    *   Version: 1.0
    *   Author: Matt Litzinger
    *   Author URI: https://litzdigital.com
    *   License: GPL2
     *
    */

Note: Do not activate the plugin yet. We will come back and do this when we are ready to view our progress.

Get Recent Photos from User Instagram Feed

The Instagram API gives us access to many requests, but for this tutorial we will be using one that retrieves the most recent photos from a specific user. It will make use of the Client ID that we set up earlier and a new identifier called the User ID. Here is what the request looks like:

https://api.instagram.com/v1/users/USER_ID/media/recent/?client_id=CLIENT_ID

Find User ID

You may be used to searching for Instagram users by their username, but the API does not use this method. Instead it identifies each user with a unique numeric string called a User ID. Unfortunately, the User ID is not as easily found as the username, but developer Ben Bjurstrom created a tool that makes it super easy.

Look Up Your Instagram ID

Once you have your User ID, add these two variables to the end of the instagram-import.php file:

$client_id = '7bb2aa2b9c3b4e679a6e9119034f55d1';
$user_id = '467550789';

Set Up JSON Request

Now that we’ve retrieved the User ID, we can create a request to retrieve the latest photos from our account using the API request mentioned earlier. Add the following code to the end of instagram-import.php.

// Get photos from Instagram
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?client_id='.$client_id; 
$args = stream_context_create(
    array('http'=>
        array(
            'timeout' => 2500,
        )
    )
);
$json_feed = file_get_contents( $url, false, $args );
$json_feed = json_decode( $json_feed );

Import Each Photo as a Single Post

Let’s look at how to import each photo as a single post. You will notice in the code above that Instagram returns the photos in a JSON object. The JSON object includes some handy meta data like the thumbnail, caption and link, which we are using to display the images on our site. The JSON object also includes other meta data which we will use for post fields like content, date, title, slug, and category.

Create New Posts for Each Photo

To save our Instagram photos as individual posts, we will use a built-in WordPress function called wp_insert_post(). This function creates a new post from an array of parameters as seen below.

foreach ($json_feed->data as $post):
    $new_post = wp_insert_post( array(
        'post_content'  => '<a href="'. esc_url( $post->link ) .'" target="_blank"><img src="'. esc_url( $post->images->standard_resolution->url ) .'" alt="'. $post->caption->text .'" /></a>',
        'post_date'     => date("Y-m-d H:i:s", $post->created_time),
        'post_date_gmt' => date("Y-m-d H:i:s", $post->created_time),
        'post_status'   => 'publish',
        'post_title'    => $post->id,
        'post_name'     => $post->id,
        'post_category' => array(2)
    ), true );
endforeach;

In the example above, we are identifying our Instagram photos from others posts by setting the post category to Instagram. If you chose to do something similar, you will need to set up the category in the Admin Panel and add the Category ID to the array (see example above) before importing your photos. WPBeginner has a helpful post on how to find a Category ID.

Another option would be to set up a custom post type specifically for Instagram photos. This solution is more complicated, but it will give you more control and a higher level of separation between your Instagram photos and other posts. If you choose to explore custom post types, be sure to check out Smashing Magazine’s The Complete Guide To Custom Post Types.

Check for Unique Photo ID

Before we check our progress on the front-end, we need to add a conditional statement that checks if the photo has already been imported to WordPress. This will prevent us from importing the same photo multiple times. Here is the function that checks if the photo has already been imported based on the post slug:

function slug_exists($post_name) {
    global $wpdb;
    if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A'))  :
        return true;
    else :
        return false;
    endif;
} 

Wrap the wp_insert_post() in the conditional statement below and add the slug_exists() function to the end of instagram-import.php. All together, it should look like this:

// Import each photo as post
foreach ($json_feed->data as $post):
    if( !the_slug_exists($post->id) ) :
        $new_post = wp_insert_post( array(
            'post_content'  => '<a href="'. esc_url( $post->link ) .'" target="_blank"><img src="'. esc_url( $post->images->standard_resolution->url ) .'" alt="'. $post->caption->text .'" /></a>',
            'post_date'     => date("Y-m-d H:i:s", $post->created_time),
            'post_date_gmt' => date("Y-m-d H:i:s", $post->created_time),
            'post_status'   => 'publish',
            'post_title'    => $post->id,
            'post_name'     => $post->id,
            'post_category' => array(2)
        ), true );
    endif;
endforeach;

function slug_exists($post_name) {
    global $wpdb;
    if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A'))  :
        return true;
    else :
        return false;
    endif;
} 

Display Photos In the Blogroll

Now we need to see if it all worked! Activate the plugin by going to the WordPress Admin Panel (under the Plugins tab) and refresh the blogroll page of the site. You should see the newly imported posts! Each post should be displaying the title, image, category, and post date.

Instagram Blog Posts

Schedule Event to Check for New Photos

Now that our photos have been imported to WordPress as posts, we need to set up a way to check for new photos and import them automatically. We don’t want to check every time a user loads the page, because the request to Instagram would be very slow and could cause performance issues with the rest of the website. Instead, we will make use of a WordPress function called wp_schedule_event().

The wp_schedule_event() function allows us to automate tasks within WordPress. To do so, we will be wrapping our existing code in a function and telling WordPress to run that function once per day. Add the following code to instagram-import.php and remember to place the existing code inside of the custom_posts_from_instagram() function.

function custom_posts_from_instagram() {
    // All of our code so far goes here
}
add_action( 'instagram_auto_fetch', 'custom_posts_from_instagram' );

if ( ! wp_next_scheduled( 'instagram_auto_fetch' ) ) {
    wp_schedule_event( time(), 'daily', 'instagram_auto_fetch');
}

WP Crontrol Plugin

WP Crontrol is a great plugin for managing event scheduling within WordPress. It allows you to see all scheduled events, edit their intervals, and delete them. It also gives you the power to create new intervals. So if you wanted your event to run four times a day, you could create a new schedule that runs every six hours. Easy, right?

WP Crontrol Plugin

Final Thoughts

As always, there is so much more you can do with a little imagination. I purposely didn’t dive in to styling or template manipulation, but I encourage you to fine-tune this to fit your project.

I was inspired to write this tutorial after redesigning my wife’s website (plaidgecko.com). She wanted to seamlessly integrate her Instagram photos with the rest of her site. We did some cool stuff with it, like hiding the photos by default (to create a bonus content effect) and only loading in photos that had a specific hashtag. The project was a great learning experience and I encourage you to check it out!

plaidGecko Website

If you are having difficulty with the tutorial here are three things to try:

  1. Check out my copy of instragram-import.php on GitHub to be sure you didn’t miss anything.
  2. Switch to a trusted theme (like TwentyTwelve) to be sure nothing there is causing the plugin to break.
  3. Disable all other plugins as one may be interfering with your code.

Project Resources

About The Author

Matt Litzinger headshot

Matt is a New Hampshire-based web developer focused on UX and digital accessibility.