自定义帖子类型的基于日期的固定链接和自定义分类固定链接

时间:2017-02-19 作者:Phil Gyford

在我的主题(一个十六岁的孩子)中,我创建了一个新的自定义帖子类型,pg_review. 我将两种自定义分类法与之关联,pg_genres (层次类别),以及pg_authors (如标签)。

除了permalinks之外,一切都很好。。。尽管试图理解和adapt various examples 我在兜圈子。

我希望这些permalinks能够发挥作用:

/reading/2017/02/19/post-name/  # A single Review.
/reading/2017/02/19/            # Reviews from one day.
/reading/2017/02/               # Reviews from one month.
/reading/2017/                  # Reviews from one year
/reading/                       # The most recent Reviews (this is working).
/reading/genre/genre-name/      # Reviews in a `pg_genre`.
/reading/author/author-name/    # Reviews in a `pg_author\'.
如果给定一个定制的permalink结构(如/archive/%year%/%monthnum%/%day%/%postname%/. 但是,如何使自定义帖子类型可以使用此功能?

(我试过Custom Post Type Permalinks plugin 它承诺做到这一点,但分类法404的链接(其他支持的人似乎也有这个问题)

1 个回复
最合适的回答,由SO网友:Milo 整理而成

我们将从分类法开始,因为它们相当简单。如果您注册这些reading/genrereading/author 作为slug 争论,这些应该没有问题。

帖子类型有点复杂。为此,我们向rewrite 参数设置为justtrue. 然后,我们为该post类型添加一个新的permastruct,其中包含:

add_permastruct(
    \'pg_review\',
    "/reading/%year%/%monthnum%/%day%/%pg_review%/",
    array( \'with_front\' => false )
);
现在我们有了单帖子视图的规则,但年/月/日视图都设置了错误的帖子类型,因此我们将添加一些新规则来重置这些规则:

add_rewrite_rule(
    \'^reading/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$\',
    \'index.php?post_type=pg_review&year=$matches[1]&monthnum=$matches[2]&day=$matches[3]\',
    \'top\'
);
add_rewrite_rule(
    \'^reading/([0-9]{4})/([0-9]{1,2})/?$\',
    \'index.php?post_type=pg_review&year=$matches[1]&monthnum=$matches[2]\',
    \'top\'
);
add_rewrite_rule(
    \'^reading/([0-9]{4})/?$\',
    \'index.php?post_type=pg_review&year=$matches[1]\',
    \'top\'
);
最后一步是过滤post_type_link 要在永久链接中插入正确的年/月/日,请执行以下操作:

function wpd_pg_review_permalinks( $url, $post ) {
    if ( \'pg_review\' == get_post_type( $post ) ) {
        $url = str_replace( "%year%", get_the_date(\'Y\'), $url );
        $url = str_replace( "%monthnum%", get_the_date(\'m\'), $url );
        $url = str_replace( "%day%", get_the_date(\'d\'), $url );
    }
    return $url;
}
add_filter( \'post_type_link\', \'wpd_pg_review_permalinks\', 10, 2 );

相关推荐

Permalinks - Archives

WordPress文档说:WordPress offers you the ability to create a custom URL structure for your permalinks and archives. https://codex.wordpress.org/Settings_Permalinks_Screen 我看到此屏幕将如何为特定帖子/页面创建永久链接,但我没有看到此设置屏幕上关于如何为存档帖子/页面创建链接的任何其他详细信息。有人能澄清一下吗?