Instagram グラフAPIで自社のInstagramアカウントの最新投稿を取得する
参考文献
https://navymobile.co.jp/instagram-graph-api
コード
<?php
// PHP
$instagram = null; // JSONデータ配列をここに格納
$instagram_business_id = '【InstagramのビジネスアカウントID番号】'; // InstagramビジネスアカウントのID
$access_token = '【アクセストークン】'; // 有効期限無期限のアクセストークン
$post_count = 9; // 表示件数
$query = 'name,media.limit(' . $post_count. '){caption,like_count,media_url,permalink,timestamp,username,comments_count}';
$get_url = 'https://graph.facebook.com/v7.0/' . $instagram_business_id . '?fields=' . $query . '&access_token=' . $access_token;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $get_url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // curl_execの結果を文字列で返す
$response = curl_exec($curl);
curl_close($curl);
if($response){
$instagram = json_decode($response);
if(isset($instagram->error)){
$instagram = null;
}
}
?>
<?php if(is_array($instagram->media->data)): ?>
<div class="instagram-container">
<?php
foreach($instagram->media->data as $post):
$caption = $post->caption;
// $caption = mb_convert_encoding($caption, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
$caption = preg_replace('/\n/', '<br>', $caption);
?>
<div class="instagram-item">
<a class="instagram-card" href="<?php echo $post->permalink; ?>" target="_blank" rel="noopener noreferrer">
<img class="instagram-card__img" src="<?php if($post->media_type=='VIDEO'){ echo $post->thumbnail_url; }else{ echo $post->media_url; } ?>" alt="<?php echo $caption; ?>">
</a>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
.instagram-container{
display: flex;
flex-wrap: wrap;
}
.instagram-item{
width: 33.333333%;
}
a.instagram-card{
display: block;
position: relative;
margin-bottom: 16px;
}
.instagram-card__img{
max-width: 100%;
height: auto;
display: block;
}
メモ:1時間くらい