Get the Category from the URL in WordPress

This bit of code will take the current URL as seen in the browser, explode (separate) it by / and then create an array that includes the category id, name, slug etc, then put’s them into variables for easy access.

This code assumes that there is only one category in the URL. If there are more it will get the first one. If there are multiple categories you could change the number below to get a different category e.g. change 1 to 2.

The example below would echo the category slug onto your page/post/template.

<?php
//GET CATEGORY FROM URL
//parse url, explode by / and put into an array
$url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);			
$url_segments = explode('/', $url_path);

$cat_slug_by_url = $url_segments[1];
$catObj = get_category_by_slug($cat_slug_by_url); 
$category_id = $catObj->term_id;
$category_name = $catObj->name;
$category_slug = $catObj->slug;
$category_count = $catObj->category_count;

echo $category_slug;
?>

Comments

We welcome comments! Please read the disclaimer.