在一页上显示 WordPress CPT 项目

Display WordPress CPT items on one page

好吧,这可能是一个非常菜鸟的问题,但我想知道如何在我的 WordPress 子主题的一页上显示所有自定义 Post 类型项目?

我的子主题有文件: functions.phpstyle.css

假设我的 CPT 名为 songs,我想在名为 example.com/music[=22 的页面上显示所有歌曲=]

有人知道如何实现吗?任何帮助将不胜感激。

当您创建名为 songs 的 CPT 时,您的 post 具有 post_type songs 和您可以像查询其他查询一样查询它 post_type 并循环打印它:

query_posts(array('post_type' => 'songs', 'posts_per_page' => '5', 'orderby' => 'date', 'order' => 'DESC', 'offset' => 0));
if(have_posts()) {
    while(have_posts()) : the_post();
        get_template_part('content', 'songs');
    endwhile;
}
wp_reset_query();

在上面的示例中,我使用可选的内容模板来呈现 post_type 的 html 以进一步构建我的代码。

所以我的模板文件夹中会有一个名为 content-songs.php 的文件,我可以在其中定义 CPT 的输出:

<article class="songs">
    <header>
        <h1><?php the_title(); ?></h1>
    </header>

    <div>
        <?php the_content(); ?>
    </div>
</article>

要在页面中输出您的 CPT,您可以使用 页面模板 ,类似于 "custom page types"。页面模板的一个简单示例是以下代码段。要使用页面模板,您需要在模板文件夹中创建一个文件,例如 page-songs.php

<?php
/**
 * Template Name: Songs
 *
 * @package WordPress
 * @subpackage YOUR THEME NAME
 * @since MyTheme 2.0
 */
get_header();

?>
    <div class="song-list">
        <?php
        query_posts(array('post_type' => 'songs', 'posts_per_page' => '5', 'orderby' => 'date', 'order' => 'DESC', 'offset' => 0));
        if(have_posts()) {
            while(have_posts()) : the_post();
                get_template_part('content', 'songs');
            endwhile;
        }
        wp_reset_query();
        ?>
    </div>
<?php
get_footer();
?>

现在 CPT 输出代码包含在页面模板中。您只需要在 Wordpress 中创建一个新页面并选择(在新出现的对话框中)页面应使用的模板。现在也可以使用模板 Songs。创建页面后,您应该会看到 CPT 的歌曲。