Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Remove Parent Category From get_the_category. WordPress

  • SOLVED

Hello!
I am looking for a way to modify get_the_category to get rid of the parent category. I am using the code below to grab categories and place them into a <li> tag.

The function works, but brings in both the child and parent category (Portfolio > Artwork). I would like to exclude the parent category, just bringing in the child category.



<?php
$categories = get_the_category();
foreach($categories as $category) {
echo str_replace('-', '', $category->slug).' ';
}
?>



Thanks!
Mike

Answers (3)

2011-07-23

Maor Barazany answers:

This will check if category does not have a parent (i.e. - it is the parent category) it will not be displayed.

<?php
$categories = get_the_category();
foreach($categories as $category) {
if ($category->category_parent == 0) continue;
echo str_replace('-', '', $category->slug).' ';

}
?>


Mike McAlister comments:

Hi Maor,
All posts will have the portfolio parent category, so this one won't work.

Mike


Maor Barazany comments:

Have you tried to check the code before deciding it won't work?
It won't display a <strong>category </strong>that does not have a parent, i.e. - the portfolio category will not be displayed.


Maor Barazany comments:

Waht @Roberto suggested may work, but it's not so efficient, why should he get all the categories twice? that will double database calls.

2011-07-23

Romel Apuya answers:

try this:
<?php
function get_deep_child_category( $categories )
{
$maxId = 0;
$maxKey = 0;
foreach ( $categories as $key => $value )
{
if ( $value->parent > $maxId )
{
$maxId = $value->term_id;
$maxKey = $key;
}
}
return $categories[$maxKey];
}

$categories = get_the_category();
if ( $categories ) :
$deepChild = get_deep_child_category( $categories );

echo str_replace('-', '', $deepChild->slug).' ';
endif;

?>


Mike McAlister comments:

That code is causing a blank loop.

Mike


Romel Apuya comments:

How about changing

echo str_replace('-', '', $deepChild->slug).' ';

to

echo str_replace('-', '', $deepChild->name).' ';


Romel Apuya comments:

or maybe try this

<?php
$categories = get_the_category();
foreach($categories as $category) {
if($category->parent!=0){
echo str_replace('-', '', $category->slug).' ';
}
}
?>

2011-07-23

Dudy wp answers:

Hi, just use this code


<ul id="nav">

<?php

$categories = get_categories('hide_empty=0');

foreach($categories as $category) {

$childs = get_categories( "hide_empty=0&child_of=" . $category->cat_ID ) ;
foreach ( $childs as $child => $value ) {
echo " | <a href=\"".get_category_link($value->cat_ID)."\" title=\"".$value->slug."\">".$value->name."</a>";
}
}

?>
</ul>