Integrating an Instagram Feed Slider in Magento 2: A Comprehensive Gui

What is Docker and what is it used for?

Integrating an Instagram Feed Slider in Magento 2: A Comprehensive Guide Social media plays a vital role in increasing the visibility of your brand and driving customer engagement.
Integrating your Instagram feed directly into your Magento 2 store can boost engagement by
showcasing your latest posts, videos, and photos in real-time. In this guide, we'll walk you through the
process of building a fully functional Instagram feed slider that loads your posts efficiently, supports
videos, and ensures fast loading times with lazy loading.

Step 1: Setting Up the Instagram Graph API
To begin, you'll need an access token from Instagram to fetch data from your Instagram account. Follow these steps to get started:
1. Create a Facebook App: Visit the Facebook Developer Portal and create a new app.
2. Generate an Access Token: Once you create the app, navigate to the Instagram Basic Display
API and generate a user access token.
3. Store Your Access Token: Save the access token somewhere secure as it will be used to
authenticate requests to the Instagram API.
For this guide, we assume you have already set up your Instagram Graph API and generated the access token.

Step 2: Building the Magento 2 Module Now that you have your access token, let’s dive into building a custom Magento 2 module to display your Instagram feed.

Step 3: Creating the Module Filesregistration.php: Registers the module in Magento.
< ?php
\Magento\Framework\Component\ComponentRegistrar::register(
\ Magento\Framework\Component\ComponentRegistrar::MODULE,
'Bluehorse_InstagramFeed',
__DIR__
);

module.xml: Defines the module name and setup version. < ?xml version="1.0"?>
< config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
< module name="Bluehorse_InstagramFeed" setup_version="1.0.0" />
< /config>

routes.xml: Sets up the route for your custom page (optional).
< ?xml version="1.0"?>
< config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
< router id="standard">
< route id="instagramfeed" frontName="instagramfeed">
< module name="Bluehorse_InstagramFeed"/>
< /route>
< /router>
< /config>

Step 4: Adding the Block Class The Block class will handle fetching data from Instagram and passing it to the template
. • Feed.php (in Block folder):
< ?php
namespace Bluehorse\InstagramFeed\Block;
class Feed extends \Magento\Framework\View\Element\Template
{
protected $accessToken;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
array $data = []
) {
$this->accessToken = 'YOUR_ACCESS_TOKEN_HERE'; // Replace with your access
token
parent::__construct($context, $data);
}
public function getInstagramFeed()
{
$json = file_get_contents("https://graph.instagram.com/me/media?
fields=id,caption,media_url,permalink,media_type,timestamp&access_token=
{$this->accessToken}");
$data = json_decode($json, true);
return isset($data['data']) ? $data['data'] : [];
}
}

Step 5: Creating the Layout and Templatedefault.xml: Calls the block and template in the page layout.
< ?xml version="1.0"?>
< page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
< body>
< referenceContainer name="content">
< block class="Bluehorse\InstagramFeed\Block\Feed"
name="instagram.feed" template="Bluehorse_InstagramFeed::feed.phtml" />
< /referenceContainer>
< /body>
< /page>

feed.phtml: Renders the Instagram posts and initializes the slider.

< ?php
$posts = $block->getInstagramFeed();
// Sort and get the first 10 posts usort($posts, function($a, $b) {
return strtotime($b['timestamp']) - strtotime($a['timestamp']);
});
$posts = array_slice($posts, 0, 10);
?>
< div class="instagram-slider">
< div class="slick-slider">
< ?php foreach ($posts as $post): ?>
< div class="instagram-post">
< a href="" target="_blank">
< ?php if ($post['media_type'] === 'IMAGE'): ?>
< img data-src="" alt="echo isset($post['caption']) ? htmlspecialchars($post['caption']) : ''; ?>" class="lazyload">
< ?php elseif ($post['media_type'] === 'VIDEO'): ?>
< video class="lazyload" controls muted>
< source data-src="" type="video/mp4">
< /video>
< ?php endif; ?>
< ?php if (isset($post['caption'])): ?>
< p>< ?php echo htmlspecialchars($post['caption']); ?>

< ?php endif; ?>
< /a>
< /div>
< ?php endforeach; ?>
< /div>
< /div>

Step 6: Optimizing the Slider with Lazy Loading Now that the posts are being fetched and displayed, let's improve the performance by implementing lazy loading. This will ensure that media assets (images and videos) are only loaded when they are about to enter the viewport, reducing initial page load time.

JavaScript for Lazy Loading
We’ll use the Intersection Observer API to lazily load media assets.
< script>
require(['jquery', 'slick', 'IntersectionObserver'], function($) {
$(document).ready(function() {
$('.slick-slider').slick({
infinite: true,
slidesToShow: 5,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 1500,
dots: false,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 4,
slidesToScroll: 1
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 3,
slidesToScroll: 1
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 2,
slidesToScroll: 1
}
}
]
}).on('init', function() {
// Lazyload after slider is initialized
var lazyImages = document.querySelectorAll('.lazyload');
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var img = entry.target;
if (img.tagName === 'IMG') {
img.src = img.getAttribute('data-src');
} else if (img.tagName === 'VIDEO') {
img.querySelector('source').src =
img.getAttribute('data-src');
img.load();
}
observer.unobserve(img);
}
});
});
lazyImages.forEach(function(img) {
observer.observe(img);
});
});
});
});
< /script>

This JavaScript ensures that the media content is only loaded when it is about to become visible to the user, improving page load speed.

Step 7: Adding Styling and Spacing
Let’s add some CSS to style the slider and ensure proper spacing around the posts. .instagram-slider {
width: 100%;
overflow: hidden;
}
.slick-slider {
display: flex;
align-items: center;
visibility: hidden; /* Hide the slider initially */
}
.slick-slide {
display: flex;
justify-content: center;
align-items: center;
}
.instagram-post {
padding: 10px;
box-sizing: border-box;
}
.instagram-post img,
.instagram-post video {
width: 100%;
height: auto;
border-radius: 10px;
}
.instagram-post a {
display: block;
text-align: center;
text-decoration: none;
color: #333;
}
.instagram-post a:hover {
text-decoration: underline;
}

Step 8: Testing and Final Touches
After implementing the above steps, be sure to test the slider on various screen
sizes and devices. Ensure that the lazy loading is functioning as
expected and that the slider is responsive.

•Clear Cache:After making these changes, clear the Magento cache and
deploy static content.
•php bin/magento cache:clean
•php bin/magento setup:static-content:deploy
•Debugging: Use the browser’s developer tools to check for any errors in the JavaScript console.

Conclusion
Integrating your Instagram feed into your Magento 2 store is a great way to increase social engagement
and keep your site content fresh. By following this guide, you've built a slick, responsive Instagram feed
slider that loads images and videos efficiently with lazy loading and improves the overall performance of
your website.

This slider can be further enhanced with custom features like lightbox popups for images, custom styling for different themes, and dynamic filters based on hashtags or categories.

Now, your Magento 2 store will dynamically showcase your latest Instagram posts, improving customer
engagement and keeping your site content visually appealing and up to date.

Comments

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.