Skip to content

Instantly share code, notes, and snippets.

@chrdesigner chrdesigner/functions.php
Last active Feb 17, 2016

Embed
What would you like to do?
List All Categories and Subcategories and return the last post register
<?php
/**
* Returns ID of top-level parent category, or current category if you are viewing a top-level
*
* @param string $catid Category ID to be checked
* @return string $catParent ID of top-level parent category
*/
function smart_category_top_parent_id ($catid) {
while ($catid) {
$cat = get_category($catid); // get the object for the catid
$catid = $cat->category_parent; // assign parent ID (if exists) to $catid
// the while loop will continue whilst there is a $catid
// when there is no longer a parent $catid will be NULL so we can assign our $catParent
$catParent = $cat->cat_ID;
}
return $catParent;
}
<ul id="menu-menu-principal" class="nav navbar-nav">
<?php
$cats = get_terms( 'category', array(
'hide_empty' => 0,
'orderby' => 'menu_order'
)
);
foreach ($cats as $cat) {
$cat_id = $cat->term_id;
$args = array(
'post_type' => 'post',
'orderby' => 'menu_order',
'order' => 'ASC',
'cat' => array( $cat_id ),
'posts_per_page' => 1,
);
$loop_cat = new WP_Query( $args );
if ($loop_cat->have_posts()) : while ($loop_cat->have_posts()) : $loop_cat->the_post();
/* Verifica o ID da categoria Parent */
$category = get_the_category($post->ID);
$catid = $category[0]->cat_ID;
$top_level_cat = smart_category_top_parent_id ($catid);
/* Adiciona a class menu-parent se existir Parent Category */
if($cat->parent == 0 ){
$addClass = ' menu-item-has-children';
}else{
$addClass = ' menu-item-hiden menu-parent-' . $top_level_cat;
};
?>
<li id="menu-item-<?php echo $cat->term_id; ?>" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-<?php echo $cat->term_id . $addClass; ?>">
<a href="<?php the_permalink();?>" title="<?php echo $cat->name; ?>"><?php echo $cat->name; ?></a>
</li>
<?php
endwhile; endif;
wp_reset_postdata();
};
?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.