Twitter Share Count for a WordPress Post

Of course this method has both advantages and disadvantages.



You can find live demo of «Tweet» button with the count at the bottom of this post.

Step 1. Custom Tweet Button

Insert this code to the place where you want to display your «Tweet» button. Just to remind you – this is only for WordPress.

	$post_id = $post->ID;
	$title = get_the_title( $post_id );
	$link = get_permalink( $post_id );
	$min_count = 1; // how much number to show if there are no tweets to the post yet
	$count = ( $count = get_post_meta( $post_id, 'post_tweets', true ) ) ? absint( $count ) : $min_count;
<a href="' . $title . '&url=' . $link . '" title="Tweet" onclick=", this.title, \'toolbar=0, status=0, width=548, height=325\'); return false" target="_parent" class="misha-tweet" data-id="' . $post_id . '" rel="noopener noreferrer">
	Tweet <span>' . $count . '</span>

Line 2 is the most important — it is where we get ID of the post. There are different ways of obtaining post ID, depending on your situation, more info you can find here.

2. Send AJAX

You need jQuery for this. It is simple – just include the jQuery script before this code.

jQuery( function( $ ){
	var ajax_url = '';
	$('.misha-tweet').click( function(){ // after clicking Tweet button
		var tweetbutton = $(this),
		    post_id = tweetbutton.attr( 'data-id' ); // get Post ID
		$.ajax({ // send the info to your server that the Tweet button has been clicked and where
			data:{'post_id' : post_id, 'action' : 'tweet'},
			success:function( data ){
				tweetbutton.find('span').text( data ); // return and display the result count

3. Increase the Count and Return Result

The code for your current WordPress theme functions.php file.

Please note, that this code has simple IP protection as well — if the same user clicks the button twice or more times, the count won’t be increased.

function misha_tweet(){

	$min_count = 1; // how much number to show if there are no tweets to the post yet
	$count = ( $count = get_post_meta( $_POST['post_id'], 'post_tweets', true ) ) ? absint( $count ) : $min_count;

	// if current user IP address == the IP of the previous user who clicked the button, skip 7-10 lines of code 
	if( get_post_meta( $_POST['post_id'], 'post_tweets_latest_ip', true ) != $_SERVER['REMOTE_ADDR'] ) {
		update_post_meta( $_POST['post_id'], 'post_tweets', $count );
		update_post_meta( $_POST['post_id'], 'post_tweets_latest_ip', $_SERVER['REMOTE_ADDR'] );

	echo $count;

add_action('wp_ajax_tweet', 'misha_tweet');
add_action('wp_ajax_nopriv_tweet', 'misha_tweet');
Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X