I have default links to my post in such format '/video/translate/continuous_present' (continuous_present
is a post name), and I want to make it look better like this '/exercise/continuous_present' but previous URL should also be available.
I tried to create a rewrite rule, it works but redirects me to the old link
add_action('init', function() {
add_permastruct('single-exercise', '^exercise/%postname%', array('with_front' => false));
flush_rewrite_rules();
}
My $wp_rewrite
variable contains such values
WP_Rewrite Object
(
[permalink_structure] => /video/%postname%
[front] => /video/
...
Here is how I register my custom post type:
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' ),
));
Any suggestions?
PS: nginx (no Apache)
After hours of googling and digging through WP's core files, I found a solution! So here is what I got
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);