列出所有自定义帖子类型的所有帖子标题与组,排除一些

时间:2018-06-18 06:30:16

标签: wordpress while-loop custom-post-type

我可以在每个自定义帖子类型中显示所有帖子标题的列表,如...

$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>';

...显示大单位列表中的所有帖子标题。

但我也希望能够做一些事情:

1)将它们与<h2>中每个组上方的自定义帖子类型名称分组,因此输出可能如下所示:

<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)允许排除特定的帖子类型。我猜测'exclude' => array('clothes', 'people'),之类的内容可能就是我所需要的,但我不确定。

提前致谢。

1 个答案:

答案 0 :(得分:1)

为您检查以下工作代码。

  $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>';