为自定义帖子类型对年度档案进行分页

时间:2013-03-27 作者:NatalieMac

下面是我用来为自定义帖子类型创建年度存档的代码:

function myquery_custom_post_rewrite( $rewrite_rules ) {
  $myqueryslug = \'customposttype\';
  $month_archive = array( $myqueryslug . \'/([0-9]{4})/?$\' => \'index.php?year=\' . $wp_rewrite->preg_index(1) . \'&post_type=\' . $myqueryslug . \'&paged=\' . $wp_rewrite->preg_index(3));
  $rewrite_rules = $month_archive + $rewrite_rules;
  return $rewrite_rules;
}
add_filter(\'rewrite_rules_array\', \'myquery_custom_post_rewrite\');
除了分页之外,这一切正常。尝试进入第2页或除第1页以外的任何页面时,总是显示404页。以下是我试图用来访问除1以外的其他页面的URL:

http://mysite.com/customposttype/year/page/2
对于customposttype,我的自定义帖子类型是slug,而对于年份,比如2012年。

我做错了什么?

=============================

更新:我成功了!以防其他人需要它,以下是使其正常工作的代码:

function myquery_custom_post_rewrite( $rewrite_rules ) {
  $pagination_base = $GLOBALS[\'wp_rewrite\']->pagination_base;
  $myqueryslug = \'customposttype\';

  $year_archive = array(
    $myqueryslug . \'/([0-9]{4})/\' . $pagination_base . \'/?([0-9]{1,})/?$\' => \'index.php?post_type=\' . $myqueryslug . \'&year=$matches[1]&paged=$matches[2]\',
    $myqueryslug . \'/([0-9]{4})/?$\' => \'index.php?post_type=\' . $myqueryslug . \'&year=$matches[1]\',
  );
  $rewrite_rules = $year_archive + $rewrite_rules;
  return $rewrite_rules;
}
add_filter(\'rewrite_rules_array\', \'myquery_custom_post_rewrite\');

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

以下是有效的代码:

function myquery_custom_post_rewrite( $rewrite_rules ) {
  $pagination_base = $GLOBALS[\'wp_rewrite\']->pagination_base;
  $myqueryslug = \'customposttype\';

  $year_archive = array(
    $myqueryslug . \'/([0-9]{4})/\' . $pagination_base . \'/?([0-9]{1,})/?$\' => \'index.php?post_type=\' . $myqueryslug . \'&year=$matches[1]&paged=$matches[2]\',
    $myqueryslug . \'/([0-9]{4})/?$\' => \'index.php?post_type=\' . $myqueryslug . \'&year=$matches[1]\',
  );
  $rewrite_rules = $year_archive + $rewrite_rules;
  return $rewrite_rules;
}
add_filter(\'rewrite_rules_array\', \'myquery_custom_post_rewrite\');

SO网友:fuxia

您的正则表达式无法工作:$wp_rewrite->preg_index(3) 与任何内容都不匹配,因为您只捕获了\'/([0-9]{4})/?$\', 不是三个。

尝试添加页面参数:

$pagination_base = $GLOBALS[\'wp_rewrite\']->pagination_base;
$month_archive = array( 
    $myqueryslug . \'/([0-9]{4})(\' . $pagination_base . \'/(\\d+))?/?$\' => 
        \'index.php?year=\' . $wp_rewrite->preg_index(1) 
        . \'&post_type=\' . $myqueryslug 
        . \'&paged=\' . $wp_rewrite->preg_index(3)
);
我还没有测试它,只是把它看作是一个指向何处的提示。

结束

相关推荐

向函数添加APPLY_FILTERS有什么不利影响吗?

我将回顾我以前的WordPress主题,使函数可过滤,并添加函数\\u exists检查。我有没有想过这会导致现有代码出现问题?// Dummy function if ( ! function_exists( \'custom_func\' )) { function custom_func() { $output = \"Something Awesome\"; return apply_filters(\'custom_func