Your code actually works for me and it is changing the theme according to the current width.
But I think you should need some tweaking something like below:
For your JavaScript:
var $ = jQuery;
$(document).ready(function() {
var windowWidth = $(window).width();
var windowHeight = $(window).height();
$.ajax( {
type: "POST",
url: "http://example.com/wp-admin/admin-ajax.php", // Must use absolute url
data: {
action: 'ajax_action',
windowWidth: windowWidth,
},
success: function(data, textStatus, XMLHttpRequest) {
alert('success ' + data); // might not be useful.
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
Use absolute URL, sometimes it won’t find the admin-ajax.php
file, because of incorrect handling of the relative URL.
For functions.php
function mmf_enqueue_scripts() {
if( !is_admin() ):
wp_enqueue_script('winsize-detect');
endif;
}
add_action( 'wp_enqueue_scripts', 'mmf_enqueue_scripts' ); // Use `wp_enqueue_scripts` instead of `wp_print_scripts`
function ajax_action() {
if( isset( $_POST['windowWidth'] ) ) {
return $_POST['windowWidth'];
}
return 0;
}
function mmf_change_theme($theme) {
// to make AJAX run only before this function
add_action('wp_ajax_ajax_action', 'ajax_action');
add_action('wp_ajax_nopriv_ajax_action', 'ajax_action');
$width = ajax_action();
//use '<='
// This might be your mistake, it worked for me.
if( $width <= 320 ) {
$theme="twentytwelve";
// if I echo the width here I get: 3203203203200 (if width=320)
}
else {
$theme="twentyteleven";
// if I echo the width here I get: 7707707707700 (if width=770)
}
return $theme;
}
add_filter('template', 'mmf_change_theme');
add_filter('option_template', 'mmf_change_theme');
add_filter('option_stylesheet', 'mmf_change_theme');
Don’t use wp_print_scripts
because its not recommended. Use wp_enqueue_scripts
instead.
Make sure don’t equal it to specific width, try less than or equal to <=
.
Replace ==
with <=