Let say a post have parent-category 'Recipes', child-category 'Baking' and post name 'My post title'
Apparently, the post can be accessible via 2 link:
I just want the post to be accessible via the first link, not the latter. Is it possible?
Many thanks!
FYI, I used /%category%/%postname%/ as custom structure for permalinks
you can use both post_link
hook and a custom rewrite rule.
custom rewrite function:
function post_add_rewrite_rule(){
$posts = get_posts( array( 'numberposts' => -1) );
if( $posts ){
foreach($posts as $post ){
$post_terms = wp_get_object_terms( $post->ID, 'recipes' );
if( $post_terms ){
add_rewrite_rule( "^recipes/" . array_pop($post_terms)->slug . "/([^/]+)/?$", 'index.php?post_type=post&name=$matches[1]', 'top' );
}
}
}
}
add_action('init', 'post_add_rewrite_rule');
post link hook:
function post_custom_permalink( $url, $post, $leavename=false ) {
if ( $post->post_type == 'post' ) {
$post_terms = wp_get_object_terms( $post->ID, 'recipes' );
if( !empty($post_terms) ){
$url = home_url( '/recipes/' . array_pop($post_terms)->slug . '/' . $post->post_name );
}
else{
$url = home_url( '/recipes/' . $post->post_name );
}
}
return $url;
}
add_filter( 'post_link', 'post_custom_permalink', 10, 3 );
and finally set up your permalink structure to custom structure:
/recipes/%postname%/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.