1

I'm trying to pull all of the categories associated with a custom post type within a loop, but I'm not sure how to get it so automatically pulls all of the categories automatically from the associated post type?

My reason is that if a user wants to add/remove a category from the custom post type, I don't want to have to edit the template file to manually add or remove the category name.

I currently have this:

<?php $args = array( 'post_type' => 'rentals');
$loop = new WP_Query( $args ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post();?>

<div class="fg12 rentals">
<h2><?php the_title(); ?></h2>
<div class="info">
  <?php category_description(); ?>
  <a class="button" href="<?php the_field('rental_item_link') ?>">
    Learn More &rarr;
  </a>
 </div>
</div>
<?php endwhile; wp_reset_query(); ?>

And I know if I add 'category_name' => 'cat-slug1, cat-slug2, etc...' it will pull those specific categories, but I'm trying to avoid doing that manually in case someone wants to add or remove a specific category.

I'm also trying to get the category description as well, but I'm not sure if I am pulling that correctly either.

I hope that makes sense.

  • You are using the categories tag and custom-taxonomy tag. Are you categories built in categories or taxonomies that you registered through register_taxonomy – Pieter Goosen Jun 19 '14 at 17:52
4

I figured it out.

I had to create a custom taxonomy and assign it to my custom post type.

Once I did that, I has to attrbute all of the custom posts to the new custom taxonomy (there's a plugin that I found that does it quickly).

then I just did a foreach loop with get_categoeries.

<?php $args = array('type' => 'rentals', 'taxonomy' => 'rental-categories');
$categories = get_categories($args);

foreach($categories as $category) {
   echo'
   <div class="fg12 rentals">
   <h2> '. $category->name . '</h2>
  <div class="info">
  <p>'. $category->description . '</p>
     <a class="button" href="#">
       Learn More &rarr;
     </a>
    </div>
   </div>';
 }
?>
  • Thank you for this. I was looking for a way to create an archive of categories (with descriptions) for users to click and go to a specific category archive. This works great. – Ricardo Andres Apr 20 '16 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.