Skip to content

Instantly share code, notes, and snippets.

@jenswittmann
Created October 20, 2020 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jenswittmann/ae7495bc704d54ab2d636da6fe04931e to your computer and use it in GitHub Desktop.
Save jenswittmann/ae7495bc704d54ab2d636da6fe04931e to your computer and use it in GitHub Desktop.
instagramLatestPosts Snippet for MODX Revolution
<?php
/**
* instagramLatestPosts
*
* DESCRIPTION
*
* This Snippet return latest posts from Instagram as iframe embed.
*
* PROPERTIES:
*
* &url required
* &tpl required
* &limit optional int
*
* USAGE:
*
* [[instagramLatestPosts?
* &url=`https://www.instagram.com/{username}/?__a=1`
* &limit=`5`
* &tpl=`@CODE:
* <figure>
* <a href="https://www.instagram.com/p/[[+shortcode]]/" target="_blank">
* <img src="[[+img]]" width="[[+img.width]]" height="[[+img.height]]">
* </a>
* <figcaption>
* [[+content]]
* </figcaption>
* </figure>
* ` ]]
*
*/
# vars
$inlineTplPrefix = '@CODE:';
$tpl = $modx->getOption('tpl', $scriptProperties, $inlineTplPrefix . ' ');
$url = $modx->getOption('url', $scriptProperties, false);
$limit = $modx->getOption('limit', $scriptProperties, 5);
# init modx rest service
$client = $modx->getService('rest', 'rest.modRest');
$client->setOption('timeout', 2);
$client->setOption('header', true);
# send request
$response = $client->get($url);
# catch login error
if ($response->responseError) {
$modx->log(
modX::LOG_LEVEL_ERROR,
'[instagramLatestPosts] ' . $response->responseError
);
return;
}
# get posts from response
$jsonData = json_decode($response->responseBody, true);
$instagramPosts =
$jsonData['graphql']['user']['edge_owner_to_timeline_media']['edges'];
if (!is_array($instagramPosts)) {
return;
}
# slice array
$instagramPosts = array_slice($instagramPosts, 0, $limit);
# set placeholders
$placeholders = [];
foreach ($instagramPosts as $postNode) {
$post = $postNode['node'];
$placeholders[] = [
'date' => $post['taken_at_timestamp'],
'username' => $post['owner']['username'],
'img' => $post['display_url'],
'img.width' => $post['dimensions']['width'],
'img.height' => $post['dimensions']['height'],
'content' => $post['edge_media_to_caption']['edges'][0]['node']['text'],
'shortcode' => $post['shortcode'],
];
}
# return
$output = [];
if (substr($tpl, 0, strlen($inlineTplPrefix)) == $inlineTplPrefix) {
$chunk = $modx->newObject('modChunk', [
'name' => '{tmp}-{' . uniqid() . '}',
]);
$chunk->setCacheable(false);
$tpl = str_replace($inlineTplPrefix, '', $tpl);
foreach ($placeholders as $placeholder) {
$output[] = $chunk->process($placeholder, $tpl);
}
} else {
foreach ($placeholders as $placeholder) {
$output[] = $modx->getChunk($tpl, $placeholder);
}
}
return implode('', $output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment