我正在尝试添加一个重写规则,以实现以下目的:
mysite/?attachment_id=106
如下所示:
mysite/series/106
我已经在这个网站和其他网站上到处找过了,这很让人困惑,因为有很多不同的方法可以做到这一点。我试过编辑
functions.php
“我的主题”文件夹中的文件,在文件开头添加以下内容:
add_rewrite_rule(\'series/([^/]+)/?$\', \'index.php?attachment_id=$matches[1]\', \'top\');
我最近试过的一个:
add_filter( \'query_vars\', \'wpa56345_query_vars\' );
function wpa56345_query_vars( $query_vars ){
$query_vars[] = \'attachment_id\';
return $query_vars;
}
add_action( \'init\', \'wpa56345_rewrites\' );
function wpa56345_rewrites(){
add_rewrite_rule(
\'series/(\\d+)/?$\',
\'index.php?attachment_id=$matches[1]\',
\'top\'
);
}
SO网友:vmassuchetto
这似乎对我有用:
// Add your query variable
add_filter( \'query_vars\', \'my_query_vars\' );
function my_query_vars( $query_vars ) {
array_push($query_vars, \'attachment_id\');
return $query_vars;
}
// Add your rule
add_filter( \'rewrite_rules_array\', \'my_rewrite_rules_array\' );
function my_rewrite_rules_array( $rules ) {
$my_rules = array();
$my_rules[\'series/(\\d+)/?$\'] = \'index.php?attachment_id=$matches[1]\';
return $my_rules + $rules;
}
// Flush the rules if your rule does not exist
add_action( \'wp_loaded\', \'my_flush_rules\' );
function my_flush_rules() {
if (!$rules = get_option(\'rewrite_rules\'))
$rules = array();
if (!isset($rules[\'series/(\\d+)/?$\'])) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
此外,如果要调试规则,还有一个有用的代码片段:
// Uncomment add_action to see what\'s happening
//add_action(\'wp\', \'debug_rules\');
function debug_rules() {
global $wp, $wp_query, $wp_rewrite;
echo $wp->matched_rule . \' | \' . $wp_rewrite->rules[$wp->matched_rule];
print_r($wp_rewrite->rules);
exit();
}
希望有帮助。