public
Last active

Create a Twitter url that enable users to Tweet an excerpt of your article using wordpress (and Advanced Custom Field if you wish so)

  • Download Gist
twitter_excerpt.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
function tweet_this($post_id){
 
//provide $post_id as argument to enable use out of the loop
 
//Fisrt get the fields if you provide different excerpts sizes :
$long_exerpt = get_field( "long_exerpt", $post_id );
$short_exerpt = get_field( "short_exerpt", $post_id );
 
//Define the max number of chars allowed in your Tweet
$max_char = 140;
 
//Test the different text sources to use as the excerpt you want to provide your user with in their tweets
if ($short_exerpt){
$excerpt = $short_exerpt;
}
elseif ($long_exerpt){
$excerpt = $long_exerpt;
}
elseif (the_excerpt()){
$excerpt = the_excerpt();
}
 
//if nothing's found, use the title as a fallback
else {
$excerpt = get_the_title($post_id);
}
 
//Start building the url
 
//Start the Tweet content
$my_tweet .= "Currently reading on example.com : ";
 
//Provide the Tweet with a link to your post
$my_tweet .= the_permalink();
// or $my_tweet .= the_shortlink();
// or alternatively $my_tweet .= site_url().'/?p='.$post_id;
 
//provide the Tweet with the excerpt created above
$my_tweet .= " " . $excerpt;
 
//Shorten the Tweet if needed
//$max_char-3 because you need to take the '...' at the end of the Tweet into account
 
$my_tweet = (strlen($my_tweet) > $max_char) ? substr($my_tweet,0,$max_char-3).'...' : $my_tweet;
$my_tweet = urlencode($my_tweet);
 
//Create the URL
$output = 'http://twitter.com/home?status='. $my_tweet;
 
return $output;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.