Skip to content

Instantly share code, notes, and snippets.

@benmay

benmay/mu-theme-switcher.php Secret

Created May 21, 2013
Embed
What would you like to do?
<?php
/*
Plugin Name: Mobile Switcher
Version: 0.1
Author: Ben May
To toggle, use the [show_theme_switch_link] shortcode.
*/
class mysiteMobile {
const key = 'my_cookie_to_set_desktop';
const theme = 'site-main-theme';
const style = 'site-mobile-theme';
private $shown = 'desktop'; // Always assumed
private $hasCookie;
public function __construct()
{
$this->hasCookie = ( isset( $_COOKIE[ self::key ] ) );
// If it's a mobile device, and there is no cookie, show mobile.
if( mysite_is_mobile() && ( !$this->hasCookie ) )
{
add_filter( 'stylesheet', array( $this, 'swap_style') );
add_filter( 'template', array( $this, 'swap_theme') );
$this->shown = 'mobile';
}
add_action( 'init', array( $this, 'redirect_header_check' ) );
add_shortcode( 'show_theme_switch_link', array( $this, 'footer_link' ) );
}
public function redirect_header_check()
{
if( isset($_GET[ self::key ] ) ):
if( $_GET[ self::key ] == 'desktop' ):
// Set cookie to force desktop for 14 days.
setcookie( self::key, true, time()+60*60*24*14);
else:
setcookie( self::key, '', current_time( 'mysql' ) - 3600 );
endif;
wp_redirect( remove_query_arg( self::key ) );
exit;
endif;
}
public function footer_link()
{
if ( $this->shown == 'mobile')
{
$return = '<a rel="external" data-ajax="false" href="?'.self::key.'=desktop">Switch to Desktop Version</a>';
}
elseif($this->hasCookie)
{
$return = '<a href="?'.self::key.'=mobile">Switch to Mobile Version</a>';
}
return $return;
}
public function swap_theme()
{
return self::theme;
}
public function swap_style()
{
return self::style;
}
}
// requires mysite_is_mobile function in wp-config
if( function_exists( 'mysite_is_mobile' ) )
$roarMobile = new mysiteMobile();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.