I’m creating a “Share this Page”– widget that needs to grab the current URL and append it to a Facebook URL like this:
http://www.facebook.com/sharer.php?u=http://myurl.com/a-specific-page
I’m using a regular text widget. How can I access the current URL and put it into the sharing link?
@user653 is correct, you can’t do it in a text widget with PHP but you can do it in a text widget using JQuery/Javascript. Here’s how.
Starting with the Facebook Share Button HTML
I assume you plan to use use the Facebook Share Button and thus will have HTML code in your widget that will look like this?
Use jQuery and
Javascript's windows.location
object.propertyIf yes then you can just add all the following code into your widget:
Be sure to Enqueue jQuery in your Theme’s
functions.php
FileHowever, in order for the above code to work you will probably need to enqueue the included jQuery script bundled with WordPress add the following line of code into your theme’s
functions.php
(unless some other plugin is already doing so):Facebook Like Button as a WordPress Shortcode
Ironically just I implemented a Facebook Like Button as a Shortcode a few days ago for a client so I thought I’d also share with you (pun intended. 😉 You can see how we got the current URL from the
$_SERVER
variable. I scarfed this exact code from theredirect_canonical()
function in/wp-includes/canonical.php'
. You can also just include this in your theme’sfunctions.php
file:What it Looks Like
Here’s a screenshot showing usage. Note that since text widgets don’t process the content filters so the shortcode doesn’t work in a text widget. I looked quickly and didn’t find a plugin that adds text widgets that can process shortcodes but it wouldn’t be hard to write one, or hard to write a widget that just adds a Facebook Share or Like buttons either. FWIW.
Hope this helps!
Just use the $_SERVER variables:
You can’t make the contents of a text widget dynamic like that.
Get “Executable PHP widget” (http://wordpress.org/extend/plugins/php-code-widget/), for example.
Now you can add your text etc including php code to insert the variable URL.
[edit]
Ref http://developers.facebook.com/docs/reference/plugins/like.
Put this into your php code supporting widget:
Here’s some complete code for you: