'WordPress generate_rewrite_rules without specific slug
Goal : I need to generate custom URL on WordPress to convert the slug into variable. Anything after slash will be considered as fruit's name.
For example, to produce banana, I need to go to website.com/u/banana
What I expected : website.com/banana
Problem : I need to remove that '/u/' part from the URL and prevent any possible conflict with other standard pages slug.
My code :
add_filter( 'generate_rewrite_rules', function ( $wp_rewrite ){
$wp_rewrite->rules = array_merge(
['u/([^/]*)' => 'index.php?fruit=$matches[1]'],
$wp_rewrite->rules
);
} );
add_filter( 'query_vars', function( $query_vars ){
$query_vars[] = 'fruit';
return $query_vars;
} );
add_filter( 'home_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template )
{
if ( get_query_var( 'fruit' ) ) :
$page_template = plugin_dir_path( __FILE__ ) . 'templates/fruitcase.php';
return $page_template;
endif;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
