I have a Photo/Wordpress site where each of my posts consist of a featured image. What i’m trying to create is to automatically post the uploaded featured image to Twitter after publishing the post. I managed to add a function to Functions.php that executes when publishing a post.
add_action('publish_post','postToTwitter');
The postToTwitter function creates a tweet with Matt Harris OAuth 1.0A library.
This works fine if i attach an image that’s relative to the file of the postToTwitter function.
// this is the jpeg file to upload. It should be in the same directory as this file.
$image = dirname(__FILE__) . '/image.jpg';
So i want the $image var to hold my Featured Image i uploaded to the WordPress post.
But this doesn’t work by just adding the URL from the uploaded image (since WordPress upload folder is not relative to the file of the postToTwitter function):
The update with media endpoint(Twitter) only supports images directly uploaded in the POST — it will not take a remote URL as an argument.
So my question is how i can refer to the Featured Image uploaded in the 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']}"
It sounds like you are simply asking how to get the image filepath instead of the url, and populate the rest of the $image string. You can get the filepath with the WordPress function
get_attached_file()
, then pass that to a few php functions to get the rest of the image metadata.By the way,
publish_post
may not be the best hook to use in this case, because according to the Codex, it is also called everytime a published post is edited. Unless you want every update to be tweeted, you might want to look at the${old_status}_to_${new_status}
hook (which passes the post object). So instead ofadd_action('publish_post','postToTwitter')
, perhaps something like this would work better:Or, if you want to alter the tweet depending on the posts’ previous status, it may be better to use this hook:
transition_post_status
because it passes the old and new statuses as arguments.