I want to switch my WordPress theme dynamically where if my visitor visits a specific URL they will see different theme while my main theme is still the same for other URLs.
All Other Pages will Show Main Theme Like Below
Only for Page wordpress-how-to-switch-theme-dynamically-by-url/ will show below Theme
WordPress Hook to Change the Theme
You can do it by using pre_option_{$option} hook. In this case:
1 2 |
pre_option_stylesheet pre_option_template |
This hook will filter the value of an existing option before it is retrieved.
You can refer the pre_option hook here.
The Code to Change WordPress Theme Dynamically
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
add_filter( 'pre_option_stylesheet', 'hdf_change_theme_stylesheet' ); add_filter( 'pre_option_template', 'hdf_change_theme_template' ); function hdf_change_theme_stylesheet(){ $current_url="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //you can change the condition based on your needs either by full URL by parameters and so on. //you can also retrieve the URL theme correspondant from database. if($current_url == 'https://www.awesomegrasp.com/wordpress-how-to-switch-theme-dynamically-by-url/'): return 'twentytwenty'; else: return "twentysixteen"; endif; } function hdf_change_theme_template(){ $current_url="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; if($current_url == 'https://www.awesomegrasp.com/wordpress-how-to-switch-theme-dynamically-by-url/'): return 'twentytwenty'; else: return "twentysixteen"; endif; } |
Don’t Put The Code at Your Theme files
It doesn’t work if you put the code at functions.php or in any files under your theme folder.
You must put at a plugin.
Side Effect by Switching WordPress Theme Dynamically
By switching the theme dynamically, I noticed that:-
- The my top main menu doesn’t appear. I don’t how to solve this yet.
- Google AdSense also seems not loaded