WordPress自定义帖子类型的替代URL

时间:2014-10-30 10:05:15

标签: php wordpress rewrite

我的帖子有默认链接,格式为' / video / translate / continuous_present' (continuous_present是一个帖子名称),我想让它看起来更像这样' / exercise / continuous_present'但以前的网址也应该可用。

我尝试创建重写规则,它可以正常工作但重定向到旧链接

add_action('init', function() {
    add_permastruct('single-exercise', '^exercise/%postname%', array('with_front' => false));
    flush_rewrite_rules();
}


我的$wp_rewrite变量包含此类值

WP_Rewrite Object
(
[permalink_structure] => /video/%postname%
[front] => /video/
...

以下是我如何注册自定义帖子类型:

register_post_type( 'translate',
    array(
        'labels' => array(
            'name' => 'Упражнения',
            'singular_name' => 'Упражнение'
        ),
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'translate'),
        'hierarchical' => true,
        'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'page-attributes', 'comments', 'revisions', 'post-formats'),
        'menu_position' => 6,
        'taxonomies' => array('translates_category', 'category'),
    )
);

register_taxonomy('translates_category',array('translate'), array(
'labels' => array(
    'name' => 'Рубрики упражнений',
    'singular_name' => __( 'Category', 'engl')
),
'hierarchical' => true,
'rewrite' => array( 'slug' => 'translates-category' ),
));

有什么建议吗?

PS: nginx(没有Apache)

1 个答案:

答案 0 :(得分:0)

经过几个小时的谷歌搜索和挖掘WP的核心文件后,我找到了解决方案!所以这就是我得到的

add_action('init', function() {
    add_rewrite_tag('%single-exercise-postname%', '([^/]+)', 'post_type=translate&name=');
    add_permastruct('single-exercise', '^exercise/%single-exercise-postname%', array('with_front' => false));
    flush_rewrite_rules(); // fire it only once
});

add_filter('post_type_link', function($post_link, $id = 0, $leavename) {
    global $wp_rewrite;
    $post = &get_post($id);
    if ( is_wp_error( $post ) )
        return $post;

    if ( $post->post_type == 'translate' ) {
        $newlink = $wp_rewrite->get_extra_permastruct('single-exercise');
        $newlink = str_replace('^', '', $newlink);
        $newlink = str_replace("%single-exercise-postname%", $post->post_name, $newlink);
        $newlink = home_url(user_trailingslashit($newlink));
        return $newlink;
    }

    return $post_link;
}, 1, 3);