1

I want to get the slug of the current archive page. I have a slider where I want to echo the products that are in this category. After hours this is all I have and it doesn't work...

<?php 

if ( is_single() ) {
    $cats =  get_the_category();
    $cat = $cats[0]; // let's just assume the post has one category
}
else { // category archives
    $cat = get_category( get_query_var( 'cat' ) );
}
$cat_name = $cat->name;
$cat_slug = $cat->slug;

echo '<h2 style="text-align:center;">'.$cat_name.' - Spotlight</h2>';
echo '<h2 style="text-align:center;">'.$cat_slug.' -- Slug</h2>';

echo "here: ".$cat_name." - ".$cat_slug;

echo do_shortcode('[wpb-product-slider title="" product_type="category" category="'.$cat_slug.'" items="3" items_desktop="3" items_desktop_small="3" items_tablet="2" items_mobile="1" width="320" height="300" crop="true" theme="ben-box" posts="50" orderby="rand" speed="2000" order="ASC"]'); ?>

But the $cat is always empty. How can I do that ?

1
  • In which file you've added this code ?
    – Sumit
    Commented Feb 19, 2016 at 15:50

2 Answers 2

1

If you are working in the "archive.php" template, you could try this code:

global $post; //maybe not needed

$category = get_the_category($post->ID);
$slug = $category[0]->slug; // try print_r($category); to see everything

echo $slug;
3
  • I don't think this works with the most recent versions of WooCommerce. I'm running 7.1.0.
    – Fred Rocha
    Commented Nov 18, 2022 at 11:13
  • @FredRocha the posted code should still work. It is no WooCommerce specfic code, this code can also be used without WooCommerce. $category = get_the_category($post->ID); simply retrieves the post categories of the provided post ID.
    – LWS-Mo
    Commented Nov 21, 2022 at 13:01
  • I get it, but it wasn't working for me. What did work was: $current_category = get_queried_object(); $current_category_slug = $current_category->slug;
    – Fred Rocha
    Commented Nov 21, 2022 at 18:57
1

What worked for me was:

$current_category = get_queried_object(); 
$current_category_slug = $current_category->slug;

I hope this might help someone, it took me way too much time to figure this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.