我有一个Photo / Wordpress网站,我的每个帖子都包含精选图片。我要创建的是在发布帖子后自动将上传的特色图片发布到Twitter。我设法将一个函数添加到Functions.php中,该函数在发布帖子时执行。
add_action('publish_post','postToTwitter');
Run Code Online (Sandbox Code Playgroud)
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';
Run Code Online (Sandbox Code Playgroud)
所以我想让$ 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']}"
Run Code Online (Sandbox Code Playgroud)
听起来您只是问如何获取图像文件路径而不是 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 );
Run Code Online (Sandbox Code Playgroud)
顺便说一下,publish_post在这种情况下可能不是最好的钩子,因为根据 Codex,每次编辑已发布的帖子时也会调用它。除非您希望在推特上发布每个更新,否则您可能需要查看钩子${old_status}_to_${new_status}(它传递 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' );
Run Code Online (Sandbox Code Playgroud)
或者,如果您想根据帖子之前的状态更改推文,最好使用此钩子:transition_post_status因为它将旧状态和新状态作为参数传递。
| 归档时间: |
|
| 查看次数: |
990 次 |
| 最近记录: |