2012-11-06 28 views
4

我有一个照片/ WordPress的网站,其中我的每个职位包括一个精选图像。我试图创建的是在发布帖子后自动将上传的精选图片发布到Twitter。我设法将一个函数添加到发布帖子时执行的Functions.php。WordPress的发布精选图片到Twitter

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']}" 
+0

更好的答案将取决于看到整个代码。如果你尝试['WP_CONTENT_DIR'](http://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Constants)怎么办? – brasofilo

回答

0

这听起来像你只是问如何得到图像文件路径而不是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可能无法在这种情况下,使用最好的钩,因为according to the Codex,它也被称为每次发布的帖子进行编辑。除非您希望每次更新都需要发送推文,否则您可能需要查看${old_status}_to_${new_status}挂钩(它会通过帖子对象)。因此,而不是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'); 

或者,如果你想改变取决于帖以前的状态的鸣叫,这可能是更好的使用这个钩子:transition_post_status,因为它通过旧的和新的状态作为论据。