javascriptphpwordpresssocialshare

Wordpress Sharer to Social Media


I wanted to make a sharing code to social media without using some plugins. i have the code the works on sharing but my problem is how can i seperated it from wordpress. for example how can i extract or get the url each posts, javascript how to seperate it, anyone to seperate it?

Here is the manual code the working. How can i apply this code to all posts???

<a class="social-share__link" href="#" target="_blank" data-href="https://www.facebook.com/sharer/sharer.php?u=https://bptapartments.com/how-renting-an-apartment-works/" onclick="javascript:window.open(this.dataset.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;"><i class="fab fa-facebook-f"></i></a>

Solution

  • you can make a function in functions.php, preferably into a child theme.

    The code could be something like this

    add_filter('the_content', 'my_content_add_fb_sharer');
    function my_content_add_fb_sharer($content){
        $urlToShare = urlencode(get_permalink());
        $fbShare = '<a class="social-share__link" href="#" target="_blank" data-href="https://www.facebook.com/sharer/sharer.php?u='.$urlToShare.'" onclick="javascript:window.open('."this.dataset.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;\"><i class=\"fab fa-facebook-f\"></i></a>'";
    
         return $content.$fbShare;
    }
    

    This will put the share link after the post content. If you want to be displayed over the content you could do

     return $fbShare.$content
    

    Also, since everything in wordpress is a post, this snippet will make this fb share link appear on ...everything!

    Hope it helps!