Spruce interactive

Noise

Display Parent Category Links with a Custom WordPress Loop

Posted: April 26th, 2013

Author: KJ Parish

Tags:

, , , , ,

 Details

Hi friends.

We’re guessing you landed here because, like us, you were trying to find some cool and simple way to ONLY display the parent of a given category or categories in a WordPress query, and this endeavor was proving to be somewhat challenging for you. We couldn’t find many awesome ways of doing this ourselves, so we came up with our own version. Read on…

Why Display the Parent?

We designed a site for a client who used a fairly elaborate category system consisting of 8 top level parent categories with 3 children under each one. The children would be offered as supportive data in rollovers and on the single article page, with the parent category taking the lead in virtually all of the rest of the page designs.

For example, on the archive page, we built a grid housing each article which would display the post thumbnail, the parent category (as a link to all posts within that parent) and the post title. The design looked something like this:

category_parent_loop

To make this happen, we needed to build a custom WordPress query that would spit out parent-specific data in our layout. We also needed it to be rather smart in the event of user error because we only wanted to display ONE parent for each article, and let’s face it…clients can’t be trusted. So, here is what we came up with:

<?php

// Variables
$numposts = 3; // How many posts do we want?

// Get Parents
$parents = new WP_Query(array(
  'posts_per_page' => $numposts,
  'hide_empty' => 0
));

// Start The Loop
while ($parents->have_posts()) : $parents->the_post();

  // Grab all post categories
  $cats = get_the_category($post->ID);
  
  // Look at the 1st category returned and get its parent. This is the key limitation here, and means that a post with multiple categories that leads to separate parents will return the parent belonging to the 1st category returned.
  $parent = get_category($cats[0]->category_parent);
  
  // Should WP throw an error message, that means we're already on the parent category.
  if (is_wp_error($parent)){
    $cat = get_category($cats[0]);
  } 
  // Otherwise, we set the category we'll be working with to be equal to the parent.
  else{
    $cat = $parent;
  }
?>

<article class="<?php echo $cat->slug;?>">

  <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
    <?php 
    if (get_the_post_thumbnail($post->ID) != '') {
      the_post_thumbnail('thumbnail');
    } ?>
  </a>  

  <h2>
    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
  </h2>

  <?php
    echo '<h3 class="cat"><a href="'.get_category_link($cat).'">'.$cat->name.'</a></h3>';  
  ?>    
  
  <div><?php the_content();?></div>
  
</article>

<?php endwhile; wp_reset_postdata();?>

Here’s what we’re doing in a nutshell:

  • Set the number of posts to display (our version is using 3)
  • Get the parents with a new WordPress query
  • Start the loop by getting all post categories and checking which one is the first returned. That way if the user goes nuts and assigns a post to all 8 parent categories we can just display the parent of the first one found and not kill the layout
  • Then, in our example we’re displaying the post thumbnail, the post title (H2), and content as usual
  • We call the special parent category link display within the H3 tag

Hope this helps. Enjoy!

  • Bea Cabrera

    Thank you!! Very clear explanation

  • Carlos Escorcio

    Thanks for the code, spot on what i needed.

  • Nicole Capili

    This really really helped me a lot! Been searching for a tutorial like this, finally found yours and used it. Thank you for sharing!

Talk to Us

Wise men have said, "All good things must come to an end", and so it was with Spruce. We began our first project in 2006, and completed our last in Fall 2013. It's been a wonderful experience, but now it's time to begin the next adventure.

Though...we wouldn't want to leave you hanging, now would we? Here are our top recommendations for world-class branding, design, and web development:

  • Kristina (KJ) Parish and Beam Collective:
    KJ provided the artistic vision that allowed Spruce to succeed, and we still think she's the greatest designer in the entire world. She's started a new collective with some talented developers, and is covering much the same territory as Spruce--design and development all under one roof, with a caliber of service and professionalism seldom seen in this business or any other. If you like what you see on the Spruce site, then definitely get in touch with KJ at kj@beamcollective.com
  • Permanent Art & Design
    Permanent is a nationally recognized design & branding firm out of Minneapolis, MN. They've been a long term collaborator and strategic partner over the past couple years, and we'd recommend them for medium to large sized businesses/organizations who are serious about putting their best foot forward. In addition to design, Permanent offers strategy and marketing services, plus in-house and networked developers. For more information contact Joseph Belk joseph@permanentadg.com
  • Nate Thompson
    A freelancer, Nate reminds us of ourselves back in the day. Smart, communicative, and skilled, Nate is our recommendation for small to medium sized businesses/organizations who have sites built on Wordpress or other open source content management solutions. With a background in both design and development, he's a one-stop shop for most web-related tasks. You can get in touch at nate.a.thompson@gmail.com
  • Kevin DeBernardi
    Designer turned developer, Kevin is embarking on a freelance web career after working as the in-house designer at the Museum of the City of New York. He's adept at translating his design ideas into custom PHP code, and is constantly expanding his technical palette. Kevin's a good choice for projects that don't quite fit into the Wordpress mold, and that would benefit from a consistency of presence and vision from design through execution. Kevin can be reached at kevin@analoglifestyle.com