使用下面的钩子,我试图重写我自定义帖子类型的永久链接magazine_issue
由我添加到编辑屏幕的其他元字段的值组成。我的实际代码的问题是,它似乎以所需的方式注册所有找到的自定义帖子的URL,但不幸的是,当请求这些页面时,它只会返回最新的通用帖子(“Hello World”)troughout。我怎样才能解决这个问题?
function magazine_issues_rewrite() {
global $wp_rewrite;
$queryarg = \'post_type=magazine_issue&p=\';
$wp_rewrite->add_rewrite_tag(\'%issuenumber%\', \'([^/]+)\', $queryarg);
$wp_rewrite->add_rewrite_tag(\'%issueyear%\', \'([^/]+)\', $queryarg);
$wp_rewrite->add_permastruct(\'issue_url_by_meta\', \'/\'.__(\'issues\', \'doev\').\'/%issueyear%/%issuenumber%/\', false);
}
add_action(\'init\', \'magazine_issues_rewrite\');
function magazine_issues_permalink($post_link, $id = 0, $leavename) {
global $wp_rewrite;
$post = &get_post($id);
if (is_wp_error($post)) return $post;
if (\'magazine_issue\'==get_post_type($post)) {
$newlink = $wp_rewrite->get_extra_permastruct(\'issue_url_by_meta\');
$newlink = str_replace("%issuenumber%", get_post_meta($post->ID,\'issuenumber\',true), $newlink);
$newlink = str_replace("%issueyear%", get_the_date(\'Y\'), $newlink);
$newlink = home_url(user_trailingslashit($newlink));
return $newlink;
}
}
add_filter(\'post_type_link\', \'magazine_issues_permalink\', 1, 3);
最合适的回答,由SO网友:Milo 整理而成
当您注册post类型时,让WordPress处理生成permastruct的过程要简单一些。我还建议不要使用全局变量,重写类需要完成的大部分工作都有API函数。
function magazine_issues_rewrite() {
add_rewrite_tag( \'%issuenumber%\', \'([^&]+)\' );
add_rewrite_tag( \'%issueyear%\', \'([^&]+)\' );
// post type registration, other args removed for clarity
$args = array(
\'rewrite\' => array( \'slug\' => \'issue/%issueyear%/%issuenumber%\' ),
);
register_post_type( \'issue\', $args );
}
add_action( \'init\', \'magazine_issues_rewrite\' );
我不确定这是否会解决您的问题,我还没有测试您的完整代码。