如何设置我的 Wordpress 模板结构来处理我的自定义 post 类型

How to set up my Wordpress template structure for handling my custom post types

我在设置 Wordpress 模板时遇到问题。我不确定如何实现以下目标。我的网站设置如下:

我有一个自定义 Post 类型 "Chapter"。 "Chapter" 是其他 CPT 的父级。我有一些 post 类型,例如:评论、采访、博客post、...

在章节页面上,我为本章中的每个 post 类型做了不同的 WP_Query。

page template single-chapter.php

现在我希望能够单击 "Blogpost (2)" 并打开当前章节中所有博客post 的存档页面。我怎样才能做到这一点?我想我应该创建一个模板页面 "archive-blogpost.php"。我已经发现我可以 link 使用此页面:

<?php echo get_post_type_archive_link( 'blogpost' ); ?>

但是我看不到这个页面怎么知道我现在在哪一章?

到目前为止我从未使用过 WP Types 插件,但您可以执行以下操作:将章节参数添加到存档 link(带有重写规则),您将进入您的博客posts 存档模板并根据此参数有条件地显示 posts。

首先我们更改存档 link 以发送章节 slug:

<?php echo get_post_type_archive_link( 'blogpost' ) . '/' . $post->post_name; ?>

然后我们在functions.php中定义这个新的rewrite tag:

function custom_rewrite_tag() {
    add_rewrite_tag('%chapter%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);

为了使 URL 看起来不错,我们将添加一个重写规则(因此您没有像 /archive/?chapter=chapter-1 那样的 url,而是 /archive/chapter-1) - 这仍然转到 functions.php:

function custom_rewrite_rule($rules) {
    add_rewrite_rule('^archive/([^/]+)/?$', 'index.php?post_type=blogposts&chapter=$matches[1]', 'top');
}
add_filter('init', 'custom_rewrite_rule', 10, 0);

您可能需要根据您的配置更改 URL / post 类型名称。

最后,您可以在博客post的存档模板中使用 $wp_query->query_vars 数组获取此查询参数:

$wp_query->query_vars['chapter']

由于我对 WP 类型知之甚少,所以我不太确定接下来的内容,但您似乎可以查询本章的子 posts:

if(isset($wp_query->query_vars['chapter']) && $chapter = get_page_by_path($wp_query->query_vars['chapter'])) {
    $childargs = array(
        'post_type' => 'blogposts',
        'numberposts' => -1,
        'meta_query' => array(array('
            key' => '_wpcf_belongs_property_id', 'value' => $chapter->ID
        ))
    );
    $child_posts = get_posts($childargs);
} else {
    // default template : display all posts
}

我使用了 WP 类型的函数来实现我想要的:

$child_posts = types_child_posts("blogpost", array('post_id' => $_GET['wpv-pr-child-of']));

有了这个,我可以从页面上的自定义 post 类型查询所有子 post。

我还使用会话变量来跟踪我所在的当前章节。