Keeping social share count after changing WordPress Permalinks

I am going to change wordpress permalinks and will do 301 redirect from old to new URL’s. But the problem is how can i keep my social sharing counts (like facebook,twitter, google +1) after the URL’s are changed.
Thanks

Related posts

Leave a Reply

1 comment

  1. Basically I am serving the old permalink for the old posts and the current permalink for the new posts.

    Here is my code if it might help.

    Create a function in your functions.php that will serve the right url for the social button :

    // Social URL function
    function social_url(){
    
        $PostDate = get_the_date('Y-m-d'); // getting the post's date
        $permalink_switch = '2014-02-07';  // change this to the date you changed the permalink
        $oldslug = basename(get_permalink()) . '.html'; // generate the old permalink slug here (in my case the permalink had an '.html' at the end. Depending on your perm link settings you might have to add a category, dates,...
    
        if($PostDate < $permalink_switch){ // if the post has been made before your permalink change it serves the old permalink
        echo 'http://www.yoursite.com/' . $oldslug;
    
        }else{ // if the post is more recent it will serve the actual permalink
        echo the_permalink();
    }
    

    Once you have this function edit your social like codes on your single.php file, in order to call the social_url() function for data-url or data-href of the social buttons

    Twitter

    <div class="tw-tweet" id="twitter-full-post"><a href="https://twitter.com/share" class="twitter-share-button" data-url="<?php social_url(); ?>" data-via="heydickface" data-lang="fr">Tweeter</a></div>
    

    Google +

    <div class="g-plusone" data-size="medium" data-href="<?php social_url(); ?>"></div>
    

    Facebook

    As a warning, Facebook seems to be less reliable than twitter or google + with this solution at least. Sometimes it works like a charm sometimes the likes drop 0 when a new click is made on the button, or stay at 0 from the beginning.

    <div class="fb-like" data-href="<?php social_url(); ?>" data-width="84" data-height="The pixel height of the plugin" data-colorscheme="light" data-layout="button_count" data-action="like" data-show-faces="false" data-send="false"></div>