Wordpress Posting

I have a Photo / Wordpress site where each of my posts consists of a tag. What I'm trying to create is to automatically post the downloaded favorite image to Twitter after the publication of the publication. I managed to add the Functions.php function, which is executed when the publication is published.

add_action('publish_post','postToTwitter'); 

The postToTwitter function creates a tweet with the Matt Harris OAuth 1.0A library. This works fine if I attach an image related 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 $ image var to store my Featured Image, which I uploaded to a Wordpress post.

But this does not work, simply adding the URL from the downloaded image (since the Wordpress download folder does not apply to the postToTwitter function file): The update with the media endpoint (Twitter) only supports images directly uploaded to POST - it will not accept as an argument remote URL.

So my question is, how can I link to Featured Image uploaded to 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']}" 
+4
source share
1 answer

It looks like you are just asking how to get the path to the image file instead of the url and fill in the rest of the image line. You can get the file path using the Wordpress get_attached_file() function, and then pass this to several php functions to get the rest of the image metadata.

 // 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 ); 

By the way, publish_post may not be the best in this case, because according to Codex , it also publishes a published message every time. If you do not want every update to be on Twitter, you can look at the ${old_status}_to_${new_status} hook (which the post object transmits). So instead of add_action('publish_post','postToTwitter') , something like this might work better:

 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' ); 

Or, if you want to change the tweet depending on the previous status of messages, it is better to use this hook: transition_post_status because it passes old and new statuses as arguments.

0
source

Source: https://habr.com/ru/post/1444370/


All Articles