PluginProbe
WP Coder – Insert & Manage Code Snippets / 4.3
WP Coder – Insert & Manage Code Snippets v4.3
4.5.1 1.1 2.3.1 2.3.2 2.4.1 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 2.5.6 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.1 3.1.1 3.2 3.2.1 3.3 3.4 3.5 3.5.1 All 39 releases
wp-coder / includes / snippets / class-tool-theme-switcher.php

class-tool-theme-switcher.php in WP Coder – Insert & Manage Code Snippets 4.3, at includes/snippets/class-tool-theme-switcher.php

73 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 defined( 'ABSPATH' ) || exit;
4
5 class WPCoder_Theme_Switcher {
6 public function __construct() {
7 add_action( 'admin_bar_menu', [ $this, 'admin_bar_item' ], 500 );
8 add_filter( 'wp_redirect', [ $this, 'handle_theme_switch_redirect' ] );
9 }
10
11 public function admin_bar_item( $admin_bar ) {
12 if ( ! current_user_can( 'manage_options' ) ) {
13 return;
14 }
15
16 $admin_bar->add_menu(
17 [
18 'id' => 'wpc-theme-toggle',
19 'group' => null,
20 'title' => '<span class="ab-icon dashicons dashicons-admin-appearance"></span><span class="ab-label">Themes</span>',
21 'href' => false,
22 'meta' => [ 'title' => __( 'Installed Themes', 'wpcoderpro' ) ],
23 ]
24 );
25
26 $themes = wp_get_themes();
27
28 foreach ( $themes as $stylesheet => $theme ) {
29 $current_theme = wp_get_theme();
30 $current_stylesheet = $current_theme->get_stylesheet();
31 $is_active = ($stylesheet === $current_stylesheet);
32 $class = 'theme-toggle';
33 $class .= $current_theme->get( 'TextDomain' ) === $theme->get( 'TextDomain' ) ? ' is-active' : '';
34 $wpnonce = wp_create_nonce( 'switch-theme_' . $stylesheet );
35 $current_url = ( isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http' ) . '://' .
36 sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ?? '' ) ) .
37 sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) );
38
39 $admin_bar->add_menu(
40 [
41 'id' => 'wpc-theme-' . $stylesheet,
42 'parent' => 'wpc-theme-toggle',
43 'title' => $theme->get( 'Name' ) . ( $is_active ? ' <span style="color:aliceblue;">✓</span>' : '' ),
44 'href' => add_query_arg(
45 [
46 'action' => 'activate',
47 'stylesheet' => $stylesheet,
48 '_wpnonce' => $wpnonce,
49 'return_url' => rawurlencode( $current_url ),
50 ],
51 admin_url( 'themes.php' )
52 ),
53 'meta' => [
54 'title' => $theme->get( 'Name' ),
55 'class' => $class,
56 ],
57 ]
58 );
59 }
60 }
61
62 public function handle_theme_switch_redirect( $location ) {
63 if (
64 isset( $_GET['return_url'], $_GET['_wpnonce'], $_GET['stylesheet'] ) &&
65 wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'switch-theme_' . sanitize_text_field( wp_unslash( $_GET['stylesheet'] ) ) ) &&
66 strpos( $location, 'themes.php' ) !== false
67 ) {
68 return esc_url_raw( urldecode( sanitize_text_field( wp_unslash( $_GET['return_url'] ) ) ) );
69 }
70 return $location;
71 }
72
73 }