Search code examples
phpwordpresswhile-loopcustom-post-type

List all post titles from all custom post types with group, exclude some


I am able to display a list of all post titles in every custom post type like this...

$args = array(
'post_type'         => 'any',
'posts_per_page'    => -1,
'exclude'           => ''
);
$loop = new WP_Query($args);
echo '<ul>';
while($loop->have_posts()): $loop->the_post(); ?>
<li><a href="<?php echo get_the_permalink(); ?>"><?php echo get_the_title(); ?></a></li>
<?php echo "\n";
endwhile;
wp_reset_query();
echo '</ul>';

...which displays all post titles in a big flat list.

But I also want to be able to do a couple of things:

1) Have them grouped with the custom post type name above each group in a <h2>, so the output might look like this for example:

<h2>Testimonials</h2>
<ul>
    <li>Some guy</li>
    <li>Some other person</li>
</ul>
<h2>Restaurants</h2>
<ul>
    <li>Chinese</li>
    <li>Indian</li>
    <li>Japanese</li>
</ul>

2) Allow specific post types to be excluded. I'm guessing something like 'exclude' => array('clothes', 'people'), might be all that's needed, but I'm unsure.

Thanks in advance.


Solution

  • Check below working code for you.

      $posttypes= array_values(get_post_types()); // get all post types
      $exclude_post_type=array('post'); // exclude the post types which you don't want to include
      $final_posttypes = array_diff($posttypes, $exclude_post_type); // this is final array which will use in post_type.
    
            $args = array(
            'post_type'         => $final_posttypes ,
            'posts_per_page'    => -1,
            'exclude'           => '',
            'orderby'=>'post_type',
            'order'=>'asc'
            );
            $loop = new WP_Query($args);
    
            echo '<ul>';
            $last_post_type='';
                while($loop->have_posts()): $loop->the_post(); 
                    $currpost_type =$post->post_type;
                    if($currpost_type!=$last_post_type) echo "<li>{$post->post_type}</li>";
                    ?>
                    <li><a href="<?php echo get_the_permalink(); ?>"><?php echo get_the_title(); ?></a></li>
                    <?php echo "\n";
                    $last_post_type = $currpost_type;
                endwhile;
            wp_reset_query();
            echo '</ul>';