Last active
December 15, 2015 07:09
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Credits to Chris Coyier for this | |
//http://css-tricks.com/snippets/wordpress/automatic-social-media-links/ | |
//http://css-tricks.com/video-screencasts/113-creating-and-using-a-custom-icon-font/ | |
<a class="social-sharing" rel="nofollow" href="<?php echo tweet_this($post_id); ?>" title="Share this article with your Twitter followers"> | |
<i aria-hidden="true" class="social-icon twitter-icon"></i> | |
<span>Tweet this !</span> | |
</a> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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