我正在尝试为一个名为“测试”的特定类别中的单个帖子创建永久链接。因此,我用一个过滤器设置了存根,该过滤器在保存帖子时反过来设置永久链接。目前,我已将其硬编码为“测试/发布1”。Stub和permalink设置得很好。然后我有一个重写规则,它将“test/post1/”写入“索引”。php?pagename=测试/post1”(再次硬编码,仅用于测试)。
这看起来很有效,但wordpress只显示了没有帖子的索引(404),所以我看到的是所有帖子页面,而不是单个帖子页面。有人知道怎么回事吗?
add_filter( \'wp_unique_post_slug\', \'filter_wp_unique_post_slug\', 10, 4 );
add_filter(\'rewrite_rules_array\',\'wp_insertMyRewriteRules\');
add_filter(\'init\',\'flushRules\');
function filter_wp_unique_post_slug( $slug, $post )
{
// Get the categories for the post
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "Test" )
{
$slug = \'test/post1\';
}
return $slug;
};
// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
$newrules = array();
$newrules[\'(.*)/(.*)/$\'] = \'index.php?pagename=test/post1\';
return $newrules + $rules;
}
// Remember to flush_rules() when adding rules
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
Edit 1
@米洛,我试过permalink过滤器,但当它不起作用时,我注意到鼻涕虫是不同的,我想可能有问题。我以前用过这个(下面)。permalink看起来像“测试/post1”,而slug看起来像“post1”。现在,我看到的所有帖子页面本身都有正确的帖子预览-它仍然不是该帖子的单个帖子页面。
add_filter( \'post_link\', \'custom_permalink\', 10, 3 );
add_filter(\'rewrite_rules_array\',\'wp_insertMyRewriteRules\');
add_filter(\'init\',\'flushRules\');
function custom_permalink( $permalink, $post, $leavename ) {
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "Test" )
{
$permalink = trailingslashit( home_url(\'test/\' . $post->post_name ) );
}
return $permalink;
}
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function wp_insertMyRewriteRules($rules)
{
$newrules = array();
$newrules[\'(.*)/(.*)/$\'] = \'index.php?name=post1\';
return $newrules + $rules;
}
最合适的回答,由SO网友:garrettlynchirl 整理而成
我不明白为什么,但regex似乎是最后一个问题。它正在捕获它,但即使有硬编码的帖子名称,它也不能正常工作。这是最终工作版本。
add_filter( \'post_link\', \'custom_permalink\', 10, 3 );
add_filter(\'rewrite_rules_array\',\'wp_insertMyRewriteRules\');
add_filter(\'init\',\'flushRules\');
function custom_permalink( $permalink, $post, $leavename ) {
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "Test" )
{
$permalink = trailingslashit( home_url(\'test/\' . $post->post_name ) );
}
return $permalink;
}
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function wp_insertMyRewriteRules($rules)
{
$newrules = array();
$newrules[\'^test/(.*)$\'] = \'index.php?name=$matches[1]\';
return $newrules + $rules;
}