change template with button

I created plugin with code :

function fxn($theme) {

if(isset($_POST['zmien'])){
    $theme = 'loose';}
else{
    $theme = 'twentytwenty';}

return $theme;
}

add_filter('template', 'fxn');
add_filter('option_template', 'fxn');
add_filter('option_stylesheet', 'fxn');

I found the code and adapted it to my website. I have created the plugin and it works only partially. When I click the button the template changes but when I click on any element on the new template the page returns to the previous template.

How can I make a change of template active until the end of browsing the page?

Topic switch themes Wordpress

Category Web


Try using switch_theme().

<?php switch_theme( $stylesheet ) ?>

I have personally never used it but it sounds like what you want. You just need to pass the stylesheet name you are using.

Here is a very basic demo I put together. You would basically but the following code, where ever its needed in both themes.

<form action="" method="post">
    <input type="radio" id="theme1" name="theme" value="theme1">
    <label for="theme1">Theme1</label><br>
    <input type="radio" id="theme2" name="theme" value="theme2">
    <label for="theme2">Theme2</label><br>
    <input type="submit" value="Submit">
</form>

<?php
    $radioVal = $_POST["theme"];

    if($radioVal == "theme1"){
        switch_theme('gemcore-ui');
        header("Refresh:0");
    }
    else if ($radioVal == "theme2"){
        switch_theme('testtheme');
    }
?>

I tested this and it worked well but I needed to refresh the page afterwards, so I added the header("Refresh:0"). Also you can add as many radio options as needed.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.