Wordpress: Get current context url

Edit: 10 Dec 2008. Changed select term_taxonomy_id to term_id.

There are many times when developing a plugin that I’ve wanted to easily get the url of the current context eg. if I’m in a category page I want the url of that page, and the same for tags archives etc.

The following function does this quite nicely.

</code>

function get_current_context_url(){
global $wp_query;
global $wpdb;

$url = '';
if (is_category()) {
$cat_id = $wp_query->query_vars['cat'];
$url = get_category_link($cat_id);
}
elseif (is_tag()) {
$tag_name = $wp_query->query_vars['tag'];
$tag_id = $wpdb->get_var("SELECT ".$wpdb->terms.".term_id FROM $wpdb->term_taxonomy
LEFT JOIN $wpdb->terms
ON (".$wpdb->term_taxonomy.".term_id = ".$wpdb->terms.".term_id)
WHERE ".$wpdb->terms.".slug = '$tag_name'
AND ".$wpdb->term_taxonomy.".taxonomy = 'post_tag'
LIMIT 1");
$url = get_tag_link($tag_id);
}
elseif (is_author()) {
$author_id = $wp_query->query_vars['author'];
$url = get_author_posts_url($author_id);
}
elseif (is_date()) {
$year = $wp_query->query_vars['year'];
$month = $wp_query->query_vars['monthnum'];
$day = $wp_query->query_vars['day'];

if ($wp_query->query_vars['day']) {
$url = get_day_link( $year,  $month,  $day);
}
elseif ($wp_query->query_vars['monthnum']) {
$url = get_month_link( $year,  $month,  $day);
}
elseif ($wp_query->query_vars['year']) {
$url = get_year_link( $year,  $month,  $day);
}
}
else {
$url = get_bloginfo('url');
}

//ensure trailing slash
if ("/" != substr($url, -1)) {
$url = $url . "/";
}
return $url;
}

<code>

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
Tagged with:
 

Comments are closed.




Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Simpler Computing - Wordpress Plugins - Help Desk Plugin