'Dynamic themes selection by user(PHP) from multiple theme

I want to add dynamic themes to my php website which will be stored from the user's database and next time when user uses the website that theme should be shown which has been selected by user and saved to database. I have searched everywhere but not getting the logic and solution as I am new to php. Please help me out.



Solution 1:[1]

The snippet below will throw an error here because of the sandboxing of the snippet but will work if copied to your own document.

The selection mechanism for different themes could be hyperlinks, buttons, radio buttons or a dropdown menu as shown here. The event listener would need to be modified to suit whatever mechanism chosen of course.

When the user makes a selection the value associated is saved to localStorage using setItem. When the page is loaded the localStorage is checked and the stylesheet is assigned the correct url.

const _STORE = 'site_SHEET';
const oSelect = document.querySelector('select[name="theme"]');

// function that saves the selected value to localStorage
const eventhandler = function(e) {
  localStorage.setItem( _STORE, this.value );
  setsheet( this.value );
};

// function to return the full path to the actual stylesheet. Change path to suit...
const setpath=( theme )=>`css/${theme}.css`;

// method to assign the new style
const setsheet=( theme )=>document.getElementById('theme').setAttribute('href', setpath( theme ) );

// Set the dropdown to the stored theme when the page loads...
const setoption=(theme)=>oSelect.value=theme;

// assign the event listener to whatever selection mechanism you use to select themes
oSelect.addEventListener('change', eventhandler );

// if the localStorage contains a selected theme, load it...
if( localStorage.getItem( _STORE )!=null ){
  setsheet( localStorage.getItem( _STORE ) );
  setoption( localStorage.getItem( _STORE ) )
}
<link rel='stylesheet' type='text/css' id='theme' />

<select name='theme'>
  <option disabled hidden selected>Select Theme
  <option value='modern'>Modern
  <option value='standard'>Standard
  <option value='dark'>Dark
  <option value='visually-impaired'>Visually-Impaired
</select>

update

I neglected to state that the above code uses four stylesheets that are named as per the options in the select menu - eg: modern.css & dark.css etc. The path to the stylesheet directory is set with the simple setpath function that has the path hardcoded into the return string ( change to suit own environment )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1