Getting current page url and title for social network sharing in WordPress

Today i added a few social network sharing buttons i.e. facebook, twitter, delicious, myspace etc. to the right side column of this very blog.  To make it work as desired I had to do some extra bit of effort to create respective urls and titles for sharing. As there seems no particular function or variable in WordPress which could give me the exact page url of the page i am currently viewing i had to create a custom function (with the help of some kind guys around the web).

So all in all, I needed exactly two parameters 1. $url and 2. $title to post links on social networking sites so here’s how i prepared them with the help of a custom function and two wordpress functions together.

For example, for facebook i would need $url and $title as shown as shown in http://www.facebook.com/share.php?src=bm&u={$url}/&t={$title}&v=3

For the $url parameter i used the following custom function which gives me the current page url:
function CurrentPageURL()  {
$pageURL = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_PORT'] != '80' ? $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"] : $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
return $pageURL;
}
$url = CurrentPageURL();

which gives me:
http://www.devarticles.in/ if it was the Home Page
http://www.devarticles.in/category/html-css/ if it was the HTML and CSS category page
http://www.devarticles.in/2010/10/ if i was the October 2010 archives page
http://www.devarticles.in/html-css/center-aligning-a-table-within-div-element/ if i was a particular (single) post page
…so on.

And for the $title i used this:
$title = get_bloginfo() . wp_title(" | ", false);
Which gives me :
devarticles.in if i was the Home Page,
devarticles.in | HTML and CSS, if i was the HTML and CSS category page
devarticles.in | 2010 | October, if i was October 2010 archives page
devarticles.in | Center aligning a table within DIV element, if i was a particular (single) post page
and so on.

Please click get_bloginfo() and wp_title() to check how these particular WordPress functions work.

I hope this helps someone.

2 thoughts on “Getting current page url and title for social network sharing in WordPress

  1. @Dusan Vlahovic – Sorry if i was late to respond. I use “Executable PHP widget” (http://wordpress.org/extend/plugins/php-code-widget/) to execute php code in the sidebar and put code with function directly there in the widget.

  2. Hi. Really useful article, but i have a couple of questions. That custom function would go on the functions.php file?, the title code also?.

    I couldn´t get it to work, and also, what´s the code you put on the sidebar?.

    Thanks a lot!.

Leave a Reply

Your email address will not be published. Required fields are marked *