Skip to content

Instantly share code, notes, and snippets.

@jongalloway
Last active October 28, 2016 23:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jongalloway/d3d797546e8d6f608a75 to your computer and use it in GitHub Desktop.
Save jongalloway/d3d797546e8d6f608a75 to your computer and use it in GitHub Desktop.
WordPress shortcodes for current page and parent urls
function get_url($atts) {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
function get_parenturl($atts) {
$url = rtrim(get_url($atts),"/");
$url = substr($url, 0, strrpos($url,"/"));
if(strlen($url)>strlen("http://" + $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"]))
return $url;
else
return "http://" + $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
}
add_shortcode('url', 'get_url');
add_shortcode('parentUrl', 'get_parenturl');
@itsananderson
Copy link

The Shortcode API wiki warns against using hyphens in shortcode names. Apparently there's a bug in the shortcode api that causes it to treat [parent] and [parent-url] as the same shortcode. This has bit me before, which is why I noticed it :)

http://codex.wordpress.org/Shortcode_API#Hyphens

As an alternative, parent_url or parentUrl should work.

@jongalloway
Copy link
Author

Thanks, changed to parentUrl.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment