首先,正确缩进代码。您的编辑器/IDE应该具有自动魔术自动缩进工具。Use them, they\'re there for a reason, 他们不仅仅是一些开发人员,他们对漂亮的代码有很高的评价。
继续,
将它们放入阵列中,而不是将其回声输出,然后在循环后对每个阵列进行回声输出
e、 g。
// this will contains arrays representing all posts of each type
$post_types = array();
// We will now use our main loop to collect data ( not print it )
while (has_posts()){ // use braces, the while(): endwhile; syntax doesn\'t play nice with editors and the highlighting
the_post;
$type = get_post_type();
// we may never have come across this type of post before, so make sure there\'s an empty array ready to receive the content
if( !isset($post_types[$type]) )
$post_types[$type] = array();
// now create the content for this post, and insert it into the array filed under the relevant post type
$post_content = \'<li>\'.get_the_title().\'</li>\';
// notice how [] will append to the end of the array without you having to figure out indexes etc
$post_types[$type][] = $post_content;
}
// now we\'ve done our main loop, lets process the data we collected and display it
foreach ( $post_types as $type => $posts ) {
// get the post types label
$label = get_post_type_object(get_post_type())->label;
echo \'<h2>\'.$label.\'</h2>\';
// display this post types content
echo \'<ul>\';
foreach($posts as $post_content ) {
echo $post_content;
}
echo \'</ul>\';
}
这将为您提供包含帖子类型的标题,然后是包含该类型帖子的无序列表。
现在您知道了如何分离帖子,并且不需要回显它们,您可以将它们保存在变量中,稍后再对其进行操作,这现在完全是一个PHP问题。考虑使用输出缓冲区简化字符串的杂耍