简体   繁体   中英

WordPress - include sub-categories in category slug

The following script outputs an icon image depending on the category slug, I would like to add in child categories of the 'Service' category - so that these will show the icon too. Would this ideally be in the form of an array?

<?php
   $category = get_the_category(); 
   $category_slug = $category[0]->slug;

   if($category_slug == 'service') {
?>
<img src="<?php echo get_template_directory_uri(); ?>/img/icon/service.png" alt="service"><span>Service</span>

<?php
}
?>

Many thanks for your help.

Yes, you can get that data and that will be array. here is a piece of code that will elaborate a bit.

<?php
$category = get_the_category(); 
$category_slug = $category[0]->slug;

if($category_slug == 'service') {
$category_id = $category->term_id;
?>
<img src="<?php echo get_template_directory_uri(); ?>/img/icon/service.png"    alt="service"><span>Service</span>

<?php
$children = get_term_children($category_id, '**your taxonomy name here**');
foreach($children as $child) {
<img src="<?php echo get_template_directory_uri(); ?>/img/icon/service.png"    alt="service">
}
}
?>

Now, paste this code in place of your code and replace your taxonomy name here with your taxonomy name. Now, your sub categories will be taking your desired image. For further reading please visit codex page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM