WP_Query to display posts by category in WordPress (in custom post types)

Hej, I’ll keep it short. I want to output this in a WP loop:

Support
    Category1
      -Post1
      -Post2
    Category2
      -PostA
      -PostB
      -PostC

So I want to order posts by category that are located in a custom post type – support (created thanks to Types plugin, link: ujeb.se/A4zqZ ).

Read More

I have this:

<?php
$args = array('post_type' => 'support');
$query = new WP_Query($args);

while($query -> have_posts()) : $query -> the_post(); ?>

    <p><?php the_category(); ?></p>
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <p><?php the_content(); ?></p>

<?php endwhile; ?>

My $query stores all the necessary posts from my custom post type (support) but I have a problem with displaying them by category. I believe I need some sort of foreach but I can’t really figure it out. Any suggestions?

/edit/
The current display looks like this:

Support, Category1
Post1
---
Support, Category2
PostA
---
Support, Category1
Post2

etc.

Related posts

2 comments

  1. Here is how you do it. You needed a foreach loop to cycle through the categories.

    <?php
    $cats = get_categories();
    
    foreach ($cats as $cat) {
    $args = array(
    'post_type' => 'support',
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => $cat->cat_ID,
            ),
        ),
    );
    $query = new WP_Query($args);
    
    if ( $query->have_posts() ): ?>
        <p><?php echo $cat->cat_name ; ?></p> <?
    
       while($query -> have_posts()) : $query -> the_post(); ?>
          <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
          <p><?php the_content(); ?></p> <?php
       endwhile;
    endif; 
    
    // Added this now 
    wp_reset_query() ; 
    }
    
  2. this work for me:

       $posts = new WP_Query(array(
            'category_name' => 'news,
            'post_status' => 'publish',
            'post_type' => 'post',
            'posts_per_page' => 6,
            ));
    

Comments are closed.