I want to send a browser info (window width) to the server via AJAX. The server doesn't need to respond with any data, however, only change the theme based on that window width.
This is my attempt:
javascript
var $ = jQuery;
$(document).ready(function() {
var windowWidth = $(window).width();
var windowHeight = $(window).height();
$.ajax( {
type: "POST",
url: ".../wp-admin/admin-ajax.php",
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);
}
});
});
functions.php
function mmf_enqueue_scripts() {
if( !is_admin() ):
wp_enqueue_script('winsize-detect');
endif;
}
add_action( 'wp_print_scripts', 'mmf_enqueue_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();
if( $width == 320 ) {
$theme = 'twentytwelve';
// if I echo the width here I get: 3203203203200 (if width=320)
}
else {
$theme = 'twentythirteen';
// 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');
I am having hard time dealing with the fact that function mmf_change_theme
is hooked, so it is called 3 times. Or I am analyzing wrongly.
How would you do it? Or how to correct my code. Also you feedback on such a method to serve different themes based on window browser size is appreciated.
I prefer not to use a plugin, which exist I know.
Thanks.