Skip to content

Instantly share code, notes, and snippets.

@benmay
Created July 24, 2012 09:50
Show Gist options
  • Save benmay/3169152 to your computer and use it in GitHub Desktop.
Save benmay/3169152 to your computer and use it in GitHub Desktop.
WordPress plugin - switching themes (used for mobile theme)
<?php
/*
Plugin Name: Mobile Theme Switcher
Description:
Version: 0.1
Author: Ben May
Author URI:
*/
class roarMobile {
const key = 'am_force_theme_layout';
const theme = 'roar';
const style = 'roar-mobile';
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( roar_is_mobile() && (! $this->hasCookie ) ):
add_filter('stylesheet', array($this, 'swap_style') );
add_filter('template', array($this, 'swap_theme') );
$this->shown = 'mobile';
endif;
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, '', time()-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 roar_is_mobile function in wp-config
if( function_exists('roar_is_mobile') ):
$roarMobile = new roarMobile();
endif;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment