2012-11-06 72 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,因爲它通過舊的和新的狀態作爲論據。