But I can’t seem to sort out how to get the $stylesheet.
Easy.
$themes = search_theme_directories();
// a random theme
$themename = array_rand($themes,1);
// that random theme's stylesheet
$stylesheet = content_url('/themes/'.$themes[$themename]['theme_file']);
// The absolute path to that theme's stylesheet
$stylepath = WP_CONTENT_DIR.'/themes/'.$themes[$themename]['theme_file'];
Getting a random theme that is not a child is more involved. I think this is it, though. It works in testing but don’t consider it rigorously tested.
$themes = search_theme_directories();
$rand_theme = false;
while (!$rand_theme) {
if (empty($themes)) {
break;
}
$themename = array_rand($themes,1);
$theme_obj = wp_get_theme($themename);
// Parent themes don't have a 'Template'
$template = $theme_obj->get('Template');
if (empty($template)) {
$rand_theme = $themename;
break;
} else {
unset($themes[$themename]);
}
}
switch_theme($rand_theme);
wp_get_theme
returns a Theme Object. I set $rand_theme
to the theme name since that is what switch_theme
expects.
As is, that will switch themes on every page load. Drop that into the plugin directory and you have yourself a pretty annoying plugin 🙂