
Photos from instagram with AJAX
First of all, we need to create a file ajax.php, in which we will write the function of obtaining photos from instagarma (more details here):
<?php // Get our data function fetchData( $url ){ $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_TIMEOUT, 20 ); $result = curl_exec( $ch ); curl_close( $ch ); return $result; } function instagram_feed( $instagram_token, $instagram_id ) { if ( $instagram_token != '' && $instagram_id != '' ){ // Pull and parse data. $result = fetchData( "https://api.instagram.com/v1/users/{$instagram_id}/media/recent/?access_token={$instagram_token}" ); $result = json_decode( $result ); $limit = 10; // Amount of images to show $i = 0; foreach ( $result->data as $post ){ if ( $i < $limit ){ echo '<a class="insta-wrap__link" rel="nofollow noopener noreferrer" target="_blank" href="' . $post->link . '">'; echo '<img class="insta-wrap__image" src="' . $post->images->thumbnail->url . '" alt="">'; echo '</a>'; $i ++; } } } } $instagram_token = 'xxx'; $instagram_id = 'xxx'; if ( $instagram_token !='' && $instagram_id != '' ) { ?> <div class="insta-wrap"> <?php instagram_feed( $instagram_token, $instagram_id ); ?> </div> <?php } ?> |
Variable $instagram_token – it’s Instagram Access Token (how to get it you can find out in this article. $instagram_id = you can find, for example, here. Just replace ‘xxx’ with your data and you will get a list of your latest photos from the instagram.
Below is the code of the page:
<html lang="ru-RU" prefix="og: http://ogp.me/ns#"> <head> </head> <body> <div class="instagram-feeds"> </div> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(window).on('load', function(){ $.ajax({ type: 'POST', url: 'ajax.php', success: function(data){ $('.instagram-feeds').html(data); } }); }); </script> </body> </html> |
That’s all, do not forget to include the jQuery library, replace $instagram_token and $instagram_id, and also correctly write the path to the ajax.php file. We tested this option and the load speed of a simple page with ten photos from the instagram on average increased in 3 times! Write, if you have any questions, we are always happy to help.
