Wordpress 将特色图片发布到 Twitter

标签 wordpress twitter

我有一个照片/Wordpress 网站,我的每个帖子都包含一张特色图片。我想要创建的是在发布帖子后自动将上传的特色图片发布到 Twitter。我设法向 Functions.php 添加了一个在发布帖子时执行的函数。

add_action('publish_post','postToTwitter');

postToTwitter 函数使用 Matt Harris OAuth 1.0A 库创建推文。
如果我附加一个与 postToTwitter 函数的文件相关的图像,这很好用。
// this is the jpeg file to upload. It should be in the same directory as this file.
$image = dirname(__FILE__) . '/image.jpg';

所以我希望 $image var 保存我上传到 Wordpress 帖子的特色图片。

但这仅通过添加上传图片中的 URL 不起作用(因为 Wordpress 上传文件夹与 postToTwitter 函数的文件无关):
使用媒体端点 (Twitter) 的更新仅支持在 POST 中直接上传的图像——它不会将远程 URL 作为参数。

所以我的问题是如何引用 POST 中上传的特色图片?
// This is how it should work with an image upload form
$image = "@{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}"

最佳答案

听起来您只是在询问如何获取图像文件路径而不是 url,并填充 $image 字符串的其余部分。您可以使用 Wordpress 函数 get_attached_file() 获取文件路径,然后将其传递给几个 php 函数以获取其余的图像元数据。

// Get featured image.
$img_id = get_post_thumbnail_id( $post->ID );
// Get image absolute filepath ($_FILES['image']['tmp_name'])
$filepath = get_attached_file( $img_id );
// Get image mime type ($_FILES['image']['type'])
//  Cleaner, but deprecated: mime_content_type( $filepath )
$mime = image_type_to_mime_type( exif_imagetype( $filepath ) );
// Get image file name ($_FILES['image']['name'])
$filename = basename( $filepath );

顺便说一句,publish_post在这种情况下可能不是最好的钩子(Hook),因为 according to the Codex ,每次编辑发布的帖子时也会调用它。除非您希望发布每个更新,否则您可能需要查看 ${old_status}_to_${new_status} 钩子(Hook)(传递 post 对象)。所以而不是add_action('publish_post','postToTwitter') ,也许这样的事情会更好:
add_action( 'new_to_publish', 'postToTwitter' );
add_action( 'draft_to_publish', 'postToTwitter' );
add_action( 'pending_to_publish', 'postToTwitter' );
add_action( 'auto-draft_to_publish', 'postToTwitter' );
add_action( 'future_to_publish', 'postToTwitter' );

或者,如果您想根据帖子的先前状态更改推文,最好使用此 Hook : transition_post_status 因为它将旧状态和新状态作为参数传递。

关于Wordpress 将特色图片发布到 Twitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13252596/

相关文章:

javascript - JS单页应用程序和基于PHP的登录系统?

php - 以编程方式更新 WordPress 帖子摘录

php - 如何使用php获取WordPress网站上发布的所有帖子

html - CSS HTML 链接图像悬停改变段落格式

perl - 如何使用 https 和 perl Dancer 将我的服务器设置为独立服务器?

javascript - 通过 Ajax 调用将 Twitter 关注按钮添加到页面

javascript - 使用我的时区在我的网站上显示推文

php - 使自定义结帐字段在 Woocommerce 管理订单单页面中显示为可编辑

javascript - 如何制作类似 "Acura"的交互式推文

java - 在 mongoDB 中存储来自 twitter api 的 json 文件