WordPress文章自动同步至Instagram实现指南
- Instagram商业账号
- 绑定Facebook主页
- 长期有效的Page Access Token
- Instagram商业账号ID(以178414开头)
实施前提
- 已完成Instagram商业账号切换,并作为管理员绑定Facebook公共主页
- 已获取长期Page Access Token及Instagram商业账号ID
- WordPress文章需设置特色图片(Instagram仅支持图文/视频内容)
PHP代码实现方案
核心流程
- 通过Meta Graph API上传图片至Instagram容器
- 发布容器内容至Instagram动态
<?php
/*
Plugin Name: WP to Instagram Auto Post
Description: Auto publish WordPress posts to Instagram Business Account via Graph API
Version: 1.0
*/
// 配置项(替换为实际信息)
define('IG_BUSINESS_ID', '178414xxxxxxxxxxxxx'); // Instagram商业ID
define('IG_PAGE_ACCESS_TOKEN', '你的长期Page Access Token');
define('IG_GRAPH_VERSION', 'v20.0');
// 文章发布触发
add_action('publish_post', 'wp_to_instagram_auto_post', 10, 2);
function wp_to_instagram_auto_post($post_id, $post){
// 仅处理新发布文章
if(wp_is_post_autosave($post_id) || wp_is_post_revision($post_id) || $post->post_status !== 'publish') {
return;
}
// 获取特色图片
$featured_image_id = get_post_thumbnail_id($post_id);
if(!$featured_image_id){
error_log('WP to Instagram: No featured image for post ' . $post_id);
return;
}
$image_url = wp_get_attachment_image_url($featured_image_id, 'full');
// 构建文案内容
$title = get_the_title($post_id);
$excerpt = wp_trim_words(get_post_field('post_excerpt', $post_id), 30);
$post_url = get_permalink($post_id);
$caption = $title . "\n\n" . $excerpt . "\n\nRead more: " . $post_url;
// 创建媒体容器
$api_url_media = "https://graph.facebook.com/" . IG_GRAPH_VERSION . "/" . IG_BUSINESS_ID . "/media";
$body_media = [
'image_url' => $image_url,
'caption' => $caption,
'access_token' => IG_PAGE_ACCESS_TOKEN
];
$response_media = wp_remote_post($api_url_media, [
'body' => $body_media,
'timeout' => 30
]);
if(is_wp_error($response_media)){
error_log('WP to Instagram Media Error: ' . $response_media->get_error_message());
return;
}
$data_media = json_decode(wp_remote_retrieve_body($response_media), true);
if(!isset($data_media['id'])){
error_log('WP to Instagram Media Failed: ' . print_r($data_media, true));
return;
}
$media_id = $data_media['id'];
// 发布媒体内容
$api_url_publish = "https://graph.facebook.com/" . IG_GRAPH_VERSION . "/" . IG_BUSINESS_ID . "/media_publish";
$body_publish = [
'creation_id' => $media_id,
'access_token' => IG_PAGE_ACCESS_TOKEN
];
$response_publish = wp_remote_post($api_url_publish, [
'body' => $body_publish,
'timeout' => 30
]);
if(is_wp_error($response_publish)){
error_log('WP to Instagram Publish Error: ' . $response_publish->get_error_message());
return;
}
$data_publish = json_decode(wp_remote_retrieve_body($response_publish), true);
if(isset($data_publish['id'])){
error_log('WP to Instagram Success: Post ' . $post_id . ' published to Instagram, ID: ' . $data_publish['id']);
}else{
error_log('WP to Instagram Publish Failed: ' . print_r($data_publish, true));
}
}
?>
常见问题解决方案
权限不足导致发布失败
确认账号为Instagram商业账号、已正确绑定Facebook主页,且使用长期Page Access Token而非用户Token
图片无法显示
需确保图片URL为公开可访问地址(禁止使用本地相对路径),推荐1:1正方形比例
文案截断问题
Instagram动态文案上限2200字符,代码已通过摘要截断处理
Token失效处理
长期Token有效期为60天,到期需重新生成并更新配置

