2
votes

is it possible to know what's the first category queried in a wordpress URL?

Example:

http://www.mywebsite.com/category/mycat/mysubcat/

My Categories hierarchy is Something Like

Parent Cat 1
Parent Cat 2
Parent Cat 3
  Subcat 1
  Subcat 2
  Subcat 3
Parent Cat 4
  Subcat 1
  Subcat 2
  Subcat 3

What i'm trying to do is to echo the "mycat" value in archive.php, to do a conditional similar to:

if($value =="mycat") { ... } else { ... }

Why it's a little bit complicated? because each post belongs to at least 1 sub-cat from each parent plus 1 of the parent category with no childs.

I need something similar to $cat = get_query_var('cat'); (in this case $cat returns mysubcat)

Any Ideas?

Thanks so much!!

2
Not sure if this is what you're looking for, but you can try using get_category_by_path() it'll give you the first category given a URL. codex.wordpress.org/Function_Reference/get_category_by_pathrexposadas

2 Answers

0
votes

Test with this simple function of WP:

<?php $thisCat = get_category(get_query_var('cat')); ?>

taken from the official directory of wordpress: https://codex.wordpress.org/Function_Reference/get_category

-1
votes

The easiest way to accomplish this is:

$uri = $_SERVER['REQUEST_URI'];
$elms = explode('/', $uri) ;
$firstcat = $elms[2] ;

if($firstcat == "products") {

// We show products grid

}

elseif($firstcat == "accesories") {

// We Show accesories grid

}

else {

// Whatever!

}