Using two permalinks for one post
I am developing a wordpress website for a client, the client want to show 2 separate templaes for post details the scenario will be.
user clicks on post and our default single.php will load up, there have a play button when user click on play button then instead of post name in permalink I want to add /play/post-name and need to load second template for that.
searched on internet and found some suggestions like Maintaining two permalink structures and https://wordpress.org/support/topic/multiple-posts-in-1-permalink
but these are not working and also these are trying to add at the end of the link but i need it to before post-name
any help will be appreciated.
thanks
Actually this is a game website and from posts listing page when user click on game image he will see a single page with game description and a play button when user click on play button he can then move to the actual game, so the post is same but we need seperate link for details and play pages.
thanks
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I’ll preface this by saying I think it makes much more sense to have play appended to the end of the permalink, which you could easily achieve with add_rewrite_endpoint, but in the interest of answering the question as it was asked…
First you’ll need to add a query var that you’ll later check to know when to load your other template:
function wpd_query_var( $query_vars ){
$query_vars[] = 'is_play';
return $query_vars;
}
add_filter('query_vars', 'wpd_query_var');
Next you’ll need a rewrite rule to handle incoming requests and set the proper query for your single post, and also set the above query var flag to load your template later.
function wpd_post_rewrite(){
add_rewrite_rule(
'play/([^/]+)/?$',
'index.php?name=$matches[1]&is_play=1',
'top'
);
}
add_action( 'init', 'wpd_post_rewrite' );
Lastly, the filter to check if the query var is set and load the other template in that case:
function wpd_play_template( $single_template ){
global $wp_query;
if ( isset( $wp_query->query_vars['is_play'] ) ) {
$single_template = locate_template( 'play_template.php', false );
}
return $single_template;
}
add_filter( 'single_template', 'wpd_play_template' );
Remember to flush your rewrite rules after changing them so the new rule gets picked up.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0