Skip to content

Instantly share code, notes, and snippets.

@charleslouis
Last active December 15, 2015 07:09
Show Gist options
  • Save charleslouis/5221436 to your computer and use it in GitHub Desktop.
Save charleslouis/5221436 to your computer and use it in GitHub Desktop.
Create a Twitter url that enable users to Tweet an excerpt of your article using wordpress (and Advanced Custom Field if you wish so)
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment