1

I have the following code on a custom wordpress page:

    <?php 
    $cat_array = array();
    $args=array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 10,
      'caller_get_posts'=> 1
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post();
        $cat_args=array('orderby' => 'none');
        $cats = wp_get_post_terms( $post->ID , 'category', $cat_args);
        foreach($cats as $cat) {
          $cat_array[$cat->term_id] = $cat->term_id;
        }
      endwhile;
    }
    if ($cat_array) {
      foreach($cat_array as $cat) {
        $category = get_term_by('ID',$cat, 'category');
        echo '<a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'.'<br />';
      }
    }
    wp_reset_query();
?>

It lists the categories in order of most recently updated category first. How do I adjust the code to get parent categories only?

Example:

Basically, I would just like to display the top level category. For example:

Category - Subcategory - Sub Subcategory - Sub Sub Subcategory

Just Category.

6
  • When you say parent categories, you mean only the categories at the very top of the tree, right?
    – mor7ifer
    Commented Jan 28, 2012 at 1:15
  • I believe so... Like when you create categories in WordPress, you can set a parent category for other categories... That's what I was referring to.
    – WordPress
    Commented Jan 28, 2012 at 1:30
  • Well yes, but a category can have a parents and grandparents, etc, I'm trying to determine if you mean show the parents of the categories, or if you mean show only categories that don't have parents at all (as in they're at the top of the tree)...if you could clarify the original question, hopefully with an example, as to what specifically you'd like to show that would be outstanding.
    – mor7ifer
    Commented Jan 28, 2012 at 1:34
  • Basically, I would just like to display the top level category. For example: Category - Subcategory - Sub Subcategory - Sub Sub Subcategory Just Category.
    – user12523
    Commented Jan 28, 2012 at 1:44
  • I got it figured out. Thank you so much for your time. I do appreciate it very much.
    – user12525
    Commented Jan 28, 2012 at 3:04

1 Answer 1

2

This should do what you're looking for. It's untested, I just whipped it up really quick right now, but the concept is there.

function my_get_highest_parent( $id ) {
    $cat = get_category( $id );
    $parent = $cat->parent;

    if( $parent == 0 ) 
        return $id;
    else
        my_get_highest_parent( $parent );
}

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.