如何按年度显示自定义帖子类型的存档(&M);月
是否按年和月自定义邮寄类型档案?
是的,你可以。您只需为wp_get_archives();
所以它接受post_type
参数:
function my_custom_post_type_archive_where($where,$args){
$post_type = isset($args[\'post_type\']) ? $args[\'post_type\'] : \'post\';
$where = "WHERE post_type = \'$post_type\' AND post_status = \'publish\'";
return $where;
}
然后称之为:add_filter( \'getarchives_where\',\'my_custom_post_type_archive_where\',10,2);
每当您想按自定义post类型显示存档文件时,只需传递post\\u类型参数:$args = array(
\'post_type\' => \'your_custom_post_type\',
\'type\' => \'monthly\',
\'echo\' => 0
);
echo \'<ul>\'.wp_get_archives($args).\'</ul>\';
你没有,Wordpress开发人员的官方说法是,自定义帖子类型并不是为了完成普通帖子的工作,如果你需要发布日期档案等,那么你做得不对,最好使用帖子格式等。。
自定义帖子类型适用于web应用程序等,而设置自定义帖子类型作为具有不同名称的辅助或并行博客(例如博客vs新闻,具有相同的功能)并不是该功能的目的,这意味着该功能的实现会产生其他技术问题。
如果您仍然坚持这一点,并且仅仅使用自定义分类法和post格式是不够的,那么您可以在函数中添加重写规则。php并将特定URL中的年/月存档重定向到后期存档页面,然后检查自定义后期存档页面,如果您在重写规则中指定了变量并加载了不同的模板,请确保在重写规则中设置适当的值。
EDIT -> 虽然这个答案仍然适用于<;WP4。4,因为4.4对自定义帖子类型的支持现在包含在wp_get_archives()
终于有了一个简单、快速、简单的解决方案,可以在WordPress中对自定义帖子类型进行基于日期的存档!这是一个长期存在的问题recorded here 在WP Core Trac中。
这一问题尚未解决,但Trac的一位贡献者发布了simple plugin in GitHub 这将使您能够为CPT建立基于日期的归档。
安装此插件后,或手动添加函数的代码后,您可以对CPT使用归档,如下所示:
<?php wp_get_archives_cpt( \'post_type=custom_post_type\' ); ?>
wp_get_archives_cpt
与标准相同wp_get_archives
因此,您可以使用它接受的任何常规参数。但是,它只是为您添加了一个自定义post类型名称参数的功能。没有足够的声誉将此添加到taiken的回答中抱歉。
然而,我想补充一点,他的回答对我来说确实有用,不过链接是“localhost/date/2010”格式的。而我需要“localhost/postslug/2010”格式。我可以通过在wp\\u get\\u归档文件的输出上使用字符串替换来修复此问题。
因此,根据permalinks的设置方式,此代码将修复404问题,并将链接重定向到自定义post类型的permalink结构:
$yearly_archive = wp_get_archives(array( \'type\' => \'yearly\', \'post_type\' => \'<your post type name>\', \'echo\' => \'0\') );
$blog_url = get_bloginfo(\'url\');
echo str_replace(($blog_url . \'/date\'), ($blog_url . \'<your post type slug>\'),$yearly_archive);
无法添加到takien的帖子中,因此以下是我最后不得不做的事情:
functions.php
add_action(\'init\', \'my_year_archive_rewrites\');
function my_year_archive_rewrites() {
add_rewrite_rule(\'resource/news/([0-9]{4})/page/?([0-9]{1,})/?\', \'index.php?post_type=news&year=$matches[1]&paged=$matches[2]\', \'top\');
add_rewrite_rule(\'resource/news/([0-9]{4})/?\', \'index.php?post_type=news&year=$matches[1]\', \'top\');
}
add_filter(\'getarchives_where\', \'my_custom_post_type_archive_where\', 10, 2);
function my_custom_post_type_archive_where($where,$args){
$post_type = isset($args[\'post_type\']) ? $args[\'post_type\'] : \'post\';
return "WHERE post_type = \'$post_type\' AND post_status = \'publish\'";
}
add_filter(\'year_link\', \'my_year_link\');
function my_year_link($link) {
global $wp_rewrite;
if(true) { // however you determine what archive you want
$link = str_replace($wp_rewrite->front, \'/resource/news/\', $link);
}
return $link;
}
Calling wp_get_archives()
wp_get_archives(array(\'post_type\'=>\'news\', \'type\'=>\'yearly\'));