I am trying to enqueue a responsive css file if the website is opened on mobile devices.
Also I want to switch / enqueue a default or non-responsive css file when a button is clicked. The non-responsive css file is the default style sheet which is loaded on desktop.
So the requirements are:
- By default a non-responsive site should be loaded if the user from desktop
- By default a responsive site should be loaded if the user from mobile
- If the user clicks a desktop switching button from mobile (responsive) site, the non-responsive site should be loaded in the mobile.
- If the user clicks a mobile switching button from mobile (non-responsive) site, the responsive site should be loaded.
I have style.css
(non-responsive css file) into my theme directory and my responsive css
file is in a folder which is into the theme directory.
- non-responsive css is file in : theme-directory/style.css
- responsive css is file in : theme-directory/css/responsive.css
And I have following buttons.
<div class="cr-athavan-lang-image">
<a href="?site=mobile" class="mobile_site" id="mobile_site"><img src="file/path/to/img" alt="switch to mobile site"></a>
<a href="?site=desktop" class="desktop_site"><img src="file/path/to/img" alt="switch to desktop site"></a>
</div>
I have added following code into my functions.php
A. To load responsive site if the user from mobile:
if ( wp_is_mobile() ){
function responsive_css(){
wp_enqueue_style(
'wpa_custom',
get_template_directory_uri() . '/css/responsive.css'
);
}
add_action( 'wp_enqueue_scripts', 'responsive_css', 999 );
}
B. To load the non-responsive site if the user clicks the button
function switch_css_file(){
if ($site == 'desktop'){
function default_css(){
wp_enqueue_style(
'default_css',
get_template_directory_uri() . '/style.css'
);
}
add_action( 'wp_enqueue_scripts', 'default_css', 999 );
}
if ($site == 'mobile'){
function default_css(){
wp_enqueue_style(
'default_css',
get_template_directory_uri() . '/css/responsive.css'
);
}
add_action( 'wp_enqueue_scripts', 'default_css', 999 );
}
}
add_action('init', 'switch_css_file', 2);
Now requirement 1 and 2 are ok.
- By default a non-responsive site is loaded if the user from desktop
- By default a responsive site is loaded if the user from mobile
I am not sure the function switch_css_file
works or NOT.
3rd and 4th requirements are not achieved yet.
If I click the desktop_site
button from the mobile the site is reloaded and still it's in responsive version.
How can I achieve 3rd & 4th requirement?
Also I think I have to set cookie during the switching.
A cookie need to be set when the desktop_site
button is clicked and should be unset when the mobile_site
is clicked.
How can I do this?