alpner
alpner

Reputation: 67

How to use WordPress post title with Twitter share button

I just bought a Genie WP theme on themeforest and I'm having an issue with share buttons, especially Twitter one.

If I click on it, it will open a twitter post tweet window with just a link in it. I would like to add (at least) post title in front of that link and not use any other plugins to do this job.

I found the part of the code that is managing social buttons, tried a couple of combinations and modifications, but nothing worked, so I'm asking you guys for help. Tnx in advance.

<?php
if ( ! function_exists( 'bt_get_share_link' ) ) {
    function bt_get_share_link( $service, $url ) {
        if ( $service == 'facebook' ) {
            return 'https://www.facebook.com/sharer/sharer.php?u=' . $url;
        } else if ( $service == 'twitter' ) {
            return 'https://twitter.com/home?status=' . $url;
        } else if ( $service == 'google_plus' ) {
            return 'https://plus.google.com/share?url=' . $url;
        } else if ( $service == 'linkedin' ) {
            return 'https://www.linkedin.com/shareArticle?url=' . $url;
        } else if ( $service == 'vk' ) {
            return 'http://vkontakte.ru/share.php?url=' . $url;     
        } else {
            return '#';
        }
    }
}

Upvotes: 1

Views: 1779

Answers (2)

Arpit Patel
Arpit Patel

Reputation: 29

Use this format for twitter to share title with link.

http://twitter.com/home?status=[Post TITLE]+[URL]

See Here.

Upvotes: 1

Michael S&#248;rensen
Michael S&#248;rensen

Reputation: 190

By adding a default argument value to the function, you don't have to change the method everywhere it's being used, if you don't want it to be required.

if ( ! function_exists( 'bt_get_share_link' ) ) {
    function bt_get_share_link( $service, $url, $title = "") {
        if ( $service == 'facebook' ) {
            return 'https://www.facebook.com/sharer/sharer.php?u=' . $url;
        } else if ( $service == 'twitter' ) {
            return $title 
                ? 'https://twitter.com/home?status='. rawurlencode($title) .'%3A%20'. $url 
                : 'https://twitter.com/home?status='. $url;
        } else if ( $service == 'google_plus' ) {
            return 'https://plus.google.com/share?url=' . $url;
        } else if ( $service == 'linkedin' ) {
            return 'https://www.linkedin.com/shareArticle?url=' . $url;
        } else if ( $service == 'vk' ) {
            return 'http://vkontakte.ru/share.php?url=' . $url;     
        } else {
            return '#';
        }
    }
}

Now you can call bt_get_share_link('twitter', 'http://google.dk'); or bt_get_share_link('twitter', 'http://google.dk', 'Hello World!');. The last method returns a url there looks like this: https://twitter.com/home?status=Hello%20World%21%3A%20http://google.dk

Instead of Hello World, you would add the post title variable as the third argument.

Upvotes: 2

Related Questions