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.
//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;
$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;
Disclaimer and Legal Information
The use of any content found on or via this website (code, how to guides etc.) is done so at your own risk. We take no responsibility for any issues encountered.
This blog and its authors will not be held responsible for any misuse, reuse, recycled and cited/uncited copies of content from this website by others.
The views and opinions expressed in this blog are those of the author(s) and do not necessarily reflect the position or opinion of any other agency, organisation, employer or company.
Comments are moderated but we do not take any responsibility for any libel or litigation that results from something written in a comment. We reserve the right to reject or delete any comment for any reason whatsoever (abusive, profane, rude etc). Please keep your comments polite and relevant.
We are happy for you to quote and share our content in any reasonable manner, e.g. post links to our blogs on social media, but not in any way that suggests that we, or our authors, endorse you, your use or your views. Nothing negative please.
We appreciate attributions, e.g. a link to our website (www.dragoncode.co.uk).