我需要以以下格式在页面上显示自定义帖子存档:
每月-本年度按月份分组每年-按年度分组;所以我有两个函数可以这样做,应该连续调用它们:
function show_monthly_archive( $post_type ) {
$current_year_args = array(
\'type\' => \'monthly\',
\'limit\' => \'12\',
\'format\' => \'html\',
\'before\' => \'\',
\'after\' => \'\',
\'show_post_count\' => false,
\'echo\' => 1,
\'order\' => \'DESC\',
\'post_type\' => $post_type
);
echo \'<ul>\';
wp_get_archives( $current_year_args );
echo \'</ul>\';
}
function show_yearly_archive( $post_type ) {
$previous_years_args = array(
\'type\' => \'yearly\',
\'limit\' => \'\',
\'format\' => \'html\',
\'before\' => \'\',
\'after\' => \'\',
\'show_post_count\' => false,
\'echo\' => 1,
\'order\' => \'DESC\',
\'post_type\' => $post_type
);
echo \'<ul>\';
wp_get_archives( $previous_years_args );
echo \'</ul>\';
}
然后我需要对其进行过滤,以便第一个函数只显示当前年份的档案,第二个函数不显示当前年份。
这样做的方式:
add_filter( \'getarchives_where\', \'filter_monthly_archives\', 10, 2 );
function filter_monthly_archives($text, $r) {
return $text . " AND YEAR(post_date) = YEAR (CURRENT_DATE)";
}
对于我们替换的年度档案
" AND YEAR(post_date) = YEAR (CURRENT_DATE)" with " AND YEAR(post_date) < YEAR (CURRENT_DATE)"
但是,过滤器全局应用,当我应用它时,它会影响两个过滤器。
有没有一种方法可以解决这个问题(为特定的wp\\u get\\u archives调用应用特定的过滤器)或其他方法来实现如上所述的归档输出?
最合适的回答,由SO网友:Pieter Goosen 整理而成
使用自定义参数,让我们调用它wpse__current_year
, 将接受两个值,true
(包括本年度)和false
(不包括本年度)。让我们合并
function show_monthly_archive( $post_type )
{
$current_year_args = array(
\'type\' => \'monthly\',
\'limit\' => \'12\',
\'format\' => \'html\',
\'before\' => \'\',
\'after\' => \'\',
\'show_post_count\' => false,
\'echo\' => 1,
\'order\' => \'DESC\',
\'post_type\' => $post_type,
\'wpse__current_year\' => true
);
echo \'<ul>\';
wp_get_archives( $current_year_args );
echo \'</ul>\';
}
function show_yearly_archive( $post_type )
{
$previous_years_args = array(
\'type\' => \'yearly\',
\'limit\' => \'\',
\'format\' => \'html\',
\'before\' => \'\',
\'after\' => \'\',
\'show_post_count\' => false,
\'echo\' => 1,
\'order\' => \'DESC\',
\'post_type\' => $post_type,
\'wpse__current_year\' => false
);
echo \'<ul>\';
wp_get_archives( $previous_years_args );
echo \'</ul>\';
}
我们现在可以相应地修改过滤器
add_filter( \'getarchives_where\', \'filter_monthly_archives\', 10, 2 );
function filter_monthly_archives( $text, $r )
{
// Check if our custom parameter is set, if not, bail early
if ( !isset( $r[\'wpse__current_year\'] ) )
return $text;
// If wpse__current_year is set to true
if ( true === $r[\'wpse__current_year\'] )
return $text . " AND YEAR(post_date) = YEAR (CURRENT_DATE)";
// If wpse__current_year is set to false
if ( false === $r[\'wpse__current_year\'] )
return $text . " AND YEAR(post_date) < YEAR (CURRENT_DATE)";
return $text;
}