查看帖子类型何时更改,并显示内容

时间:2013-02-19 作者:Richard Ascough

以下代码是在另一个问题中提供的,但似乎不起作用。基本上,我有4种帖子类型(交易、住宿、文章、景点),我想显示一个与常见分类法(目的地)相关的帖子类型列表,并使用标题分隔每个分类法。

目的地:伦敦旅游景点

有什么想法吗?我已将其添加到分类目标。php,但它似乎只是挂起了。

<?php
$post_type = \'\';
while (has_posts()): the_post;

if (get_post_type() !== $post_type) {
    // print the header for the post type
    // maybe something like this...
    echo \'<h2>\', esc_html(get_post_type_object(get_post_type())->label)), \'</h2>\';
}

// do stuff with the current post

$post_type = get_post_type();

endwhile;

1 个回复
SO网友:Tom J Nowell

首先,正确缩进代码。您的编辑器/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问题。考虑使用输出缓冲区简化字符串的杂耍

结束

相关推荐