Açıklama Yok

class-jetpack-instant-search.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. <?php
  2. /**
  3. * Jetpack Search: Instant Front-End Search and Filtering
  4. *
  5. * @since 8.3.0
  6. * @package automattic/jetpack
  7. */
  8. /**
  9. * Class to load Instant Search experience on the site.
  10. *
  11. * @since 8.3.0
  12. */
  13. class Jetpack_Instant_Search extends Jetpack_Search {
  14. /**
  15. * The name of instant search sidebar
  16. *
  17. * @since 9.8.0
  18. *
  19. * @var string
  20. */
  21. const JETPACK_INSTANT_SEARCH_SIDEBAR = 'jetpack-instant-search-sidebar';
  22. /**
  23. * Variable to save old sidebars_widgets value.
  24. *
  25. * The value is set when action `after_switch_theme` is applied and cleared on filter `pre_update_option_sidebars_widgets`.
  26. * The filters mentioned above run on /wp-admin/themes.php?activated=true, a request closely following switching theme.
  27. *
  28. * @since 9.8.0
  29. *
  30. * @var array
  31. */
  32. protected $old_sidebars_widgets;
  33. /**
  34. * Get singleton instance of Jetpack Instant Search.
  35. *
  36. * Instantiates and sets up a new instance if needed, or returns the singleton.
  37. *
  38. * @since 9.8.0
  39. *
  40. * @return Jetpack_Instant_Search The Jetpack_Instant_Search singleton.
  41. */
  42. public static function instance() {
  43. if ( ! isset( self::$instance ) ) {
  44. self::$instance = new static();
  45. self::$instance->setup();
  46. }
  47. return self::$instance;
  48. }
  49. /**
  50. * Loads the php for this version of search
  51. *
  52. * @since 8.3.0
  53. */
  54. public function load_php() {
  55. $this->base_load_php();
  56. require_once __DIR__ . '/class-jetpack-search-settings.php';
  57. new Jetpack_Search_Settings();
  58. if ( class_exists( 'WP_Customize_Manager' ) ) {
  59. require_once __DIR__ . '/class-jetpack-search-customize.php';
  60. new Jetpack_Search_Customize();
  61. }
  62. }
  63. /**
  64. * Setup the various hooks needed for the plugin to take over search duties.
  65. *
  66. * @since 5.0.0
  67. */
  68. public function init_hooks() {
  69. if ( ! is_admin() ) {
  70. add_filter( 'posts_pre_query', array( $this, 'filter__posts_pre_query' ), 10, 2 );
  71. add_action( 'parse_query', array( $this, 'action__parse_query' ), 10, 1 );
  72. add_action( 'init', array( $this, 'set_filters_from_widgets' ) );
  73. add_action( 'wp_enqueue_scripts', array( $this, 'load_assets' ) );
  74. add_action( 'wp_footer', array( 'Jetpack_Search_Helpers', 'print_instant_search_sidebar' ) );
  75. add_filter( 'body_class', array( $this, 'add_body_class' ), 10 );
  76. } else {
  77. add_action( 'update_option', array( $this, 'track_widget_updates' ), 10, 3 );
  78. }
  79. /**
  80. * Note:
  81. * 1. The priority has to be lower than 10 to run before _wp_sidebars_changed.
  82. * Which migrates widgets from old theme to the new one.
  83. * 2. WP.com runs after_switch_theme hook from the frontend, so we'll need to hook it.
  84. * No matter it's admin or frontend.
  85. */
  86. add_action( 'after_switch_theme', array( $this, 'save_old_sidebars_widgets' ), 5, 0 );
  87. add_action( 'pre_update_option_sidebars_widgets', array( $this, 'remove_wp_migrated_widgets' ) );
  88. add_action( 'widgets_init', array( $this, 'register_jetpack_instant_sidebar' ) );
  89. add_action( 'jetpack_deactivate_module_search', array( $this, 'move_search_widgets_to_inactive' ) );
  90. }
  91. /**
  92. * Loads assets for Jetpack Instant Search Prototype featuring Search As You Type experience.
  93. */
  94. public function load_assets() {
  95. $this->load_assets_with_parameters( '', JETPACK__PLUGIN_FILE );
  96. }
  97. /**
  98. * Loads assets according to parameters provided.
  99. *
  100. * @param string $path_prefix - Prefix for assets' relative paths.
  101. * @param string $plugin_base_path - Base path for use in plugins_url.
  102. */
  103. public function load_assets_with_parameters( $path_prefix, $plugin_base_path ) {
  104. $script_relative_path = $path_prefix . '_inc/build/instant-search/jp-search-main.bundle.js';
  105. if ( ! file_exists( JETPACK__PLUGIN_DIR . $script_relative_path ) ) {
  106. return;
  107. }
  108. $script_version = Jetpack_Search_Helpers::get_asset_version( $script_relative_path );
  109. $script_path = plugins_url( $script_relative_path, $plugin_base_path );
  110. wp_enqueue_script( 'jetpack-instant-search', $script_path, array(), $script_version, true );
  111. wp_set_script_translations( 'jetpack-instant-search', 'jetpack' );
  112. $this->load_and_initialize_tracks();
  113. $this->inject_javascript_options();
  114. // It only inline the translations for the script, but does not load it.
  115. $this->inject_translation_for_script(
  116. plugins_url(
  117. $path_prefix . '_inc/build/instant-search/jp-search.chunk-main-payload.min.js',
  118. $plugin_base_path
  119. )
  120. );
  121. }
  122. /**
  123. * Add inline translations for script `$payload_url` before loading `$before_handle` script.
  124. *
  125. * @param string $payload_url - The payload url for which we load the translations.
  126. * @param string $before_handle - Inline the translations before this handle.
  127. */
  128. protected function inject_translation_for_script( $payload_url, $before_handle = 'jetpack-instant-search' ) {
  129. // Set a random name for the script.
  130. $handle = 'jetpack-instant-search-' . wp_unique_id();
  131. // Then register it, which is required for the next steps.
  132. // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NoExplicitVersion
  133. wp_register_script( $handle, $payload_url, array(), false, false );
  134. // Set translation domain to `jetpack`, and we need to explicitly set the `path` to load translations files for WPCOM.
  135. // Otherwise WPCOM would try to load from `WP_LANG_DIR . '/mu-plugins'` and fails.
  136. wp_set_script_translations( $handle, 'jetpack', WP_LANG_DIR . '/plugins' );
  137. // Inline the translations before `$before_handle` handle.
  138. wp_add_inline_script( $before_handle, wp_scripts()->print_translations( $handle, false ), 'before' );
  139. // Deregister the script as we don't really enqueue it from PHP side.
  140. wp_deregister_script( $handle );
  141. }
  142. /**
  143. * Passes all options to the JS app.
  144. */
  145. protected function inject_javascript_options() {
  146. $options = Jetpack_Search_Helpers::generate_initial_javascript_state();
  147. // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
  148. wp_add_inline_script( 'jetpack-instant-search', 'var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("' . rawurlencode( wp_json_encode( $options ) ) . '"));', 'before' );
  149. }
  150. /**
  151. * Registers a widget sidebar for Instant Search.
  152. */
  153. public function register_jetpack_instant_sidebar() {
  154. $args = array(
  155. 'name' => __( 'Jetpack Search Sidebar', 'jetpack' ),
  156. 'id' => 'jetpack-instant-search-sidebar',
  157. 'description' => __( 'Customize the sidebar inside the Jetpack Search overlay', 'jetpack' ),
  158. 'class' => '',
  159. 'before_widget' => '<div id="%1$s" class="widget %2$s">',
  160. 'after_widget' => '</div>',
  161. 'before_title' => '<h2 class="widgettitle">',
  162. 'after_title' => '</h2>',
  163. );
  164. register_sidebar( $args );
  165. }
  166. /**
  167. * Loads scripts for Tracks analytics library
  168. */
  169. public function load_and_initialize_tracks() {
  170. wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
  171. }
  172. /**
  173. * Bypass the normal Search query since we will run it with instant search.
  174. *
  175. * @since 8.3.0
  176. *
  177. * @param array $posts Current array of posts (still pre-query).
  178. * @param WP_Query $query The WP_Query being filtered.
  179. *
  180. * @return array Array of matching posts.
  181. */
  182. public function filter__posts_pre_query( $posts, $query ) {
  183. if ( ! $this->should_handle_query( $query ) ) {
  184. // Intentionally not adding the 'jetpack_search_abort' action since this should fire for every request except for search.
  185. return $posts;
  186. }
  187. /**
  188. * Bypass the main query and return dummy data
  189. * WP Core doesn't call the set_found_posts and its filters when filtering
  190. * posts_pre_query like we do, so need to do these manually.
  191. */
  192. $query->found_posts = 1;
  193. $query->max_num_pages = 1;
  194. return array();
  195. }
  196. /**
  197. * Run the aggregations API query for any filtering
  198. *
  199. * @since 8.3.0
  200. */
  201. public function action__parse_query() {
  202. if ( ! empty( $this->search_result ) ) {
  203. return;
  204. }
  205. if ( is_admin() ) {
  206. return;
  207. }
  208. if ( empty( $this->aggregations ) ) {
  209. return;
  210. }
  211. jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-builder' );
  212. $builder = new Jetpack_WPES_Query_Builder();
  213. $this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
  214. $this->search_result = $this->instant_api(
  215. array(
  216. 'aggregations' => $builder->build_aggregation(),
  217. 'size' => 0,
  218. 'from' => 0,
  219. )
  220. );
  221. }
  222. /**
  223. * Run an instant search on the WordPress.com public API.
  224. *
  225. * @since 8.3.0
  226. *
  227. * @param array $args Args conforming to the WP.com v1.3/sites/<blog_id>/search endpoint.
  228. *
  229. * @return object|WP_Error The response from the public API, or a WP_Error.
  230. */
  231. public function instant_api( array $args ) {
  232. global $wp_version;
  233. $start_time = microtime( true );
  234. // Cache locally to avoid remote request slowing the page.
  235. $transient_name = 'jetpack_instant_search_cache_' . md5( wp_json_encode( $args ) );
  236. $cache = get_transient( $transient_name );
  237. if ( false !== $cache ) {
  238. return $cache;
  239. }
  240. $service_url = add_query_arg(
  241. $args,
  242. sprintf(
  243. 'https://public-api.wordpress.com/rest/v1.3/sites/%d/search',
  244. $this->jetpack_blog_id
  245. )
  246. );
  247. $request_args = array(
  248. 'timeout' => 10,
  249. 'user-agent' => "WordPress/{$wp_version} | Jetpack/" . constant( 'JETPACK__VERSION' ),
  250. );
  251. $request = wp_remote_get( esc_url_raw( $service_url ), $request_args );
  252. $end_time = microtime( true );
  253. if ( is_wp_error( $request ) ) {
  254. return $request;
  255. }
  256. $response_code = wp_remote_retrieve_response_code( $request );
  257. $response = json_decode( wp_remote_retrieve_body( $request ), true );
  258. if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
  259. /**
  260. * Fires after a search query request has failed
  261. *
  262. * @module search
  263. *
  264. * @since 5.6.0
  265. *
  266. * @param array Array containing the response code and response from the failed search query
  267. */
  268. do_action(
  269. 'failed_jetpack_search_query',
  270. array(
  271. 'response_code' => $response_code,
  272. 'json' => $response,
  273. )
  274. );
  275. return new WP_Error( 'invalid_search_api_response', 'Invalid response from API - ' . $response_code );
  276. }
  277. $took = is_array( $response ) && ! empty( $response['took'] )
  278. ? $response['took']
  279. : null;
  280. $query = array(
  281. 'args' => $args,
  282. 'response' => $response,
  283. 'response_code' => $response_code,
  284. 'elapsed_time' => ( $end_time - $start_time ) * 1000, // Convert from float seconds to ms.
  285. 'es_time' => $took,
  286. 'url' => $service_url,
  287. );
  288. /**
  289. * Fires after a search request has been performed.
  290. *
  291. * Includes the following info in the $query parameter:
  292. *
  293. * array args Array of Elasticsearch arguments for the search
  294. * array response Raw API response, JSON decoded
  295. * int response_code HTTP response code of the request
  296. * float elapsed_time Roundtrip time of the search request, in milliseconds
  297. * float es_time Amount of time Elasticsearch spent running the request, in milliseconds
  298. * string url API url that was queried
  299. *
  300. * @module search
  301. *
  302. * @since 5.0.0
  303. * @since 5.8.0 This action now fires on all queries instead of just successful queries.
  304. *
  305. * @param array $query Array of information about the query performed
  306. */
  307. do_action( 'did_jetpack_search_query', $query );
  308. // Update local cache.
  309. set_transient( $transient_name, $response, 1 * HOUR_IN_SECONDS );
  310. return $response;
  311. }
  312. /**
  313. * Get the raw Aggregation results from the Elasticsearch response.
  314. *
  315. * @since 8.4.0
  316. *
  317. * @return array Array of Aggregations performed on the search.
  318. */
  319. public function get_search_aggregations_results() {
  320. if ( empty( $this->search_result ) || is_wp_error( $this->search_result ) || ! isset( $this->search_result['aggregations'] ) ) {
  321. return array();
  322. }
  323. return $this->search_result['aggregations'];
  324. }
  325. /**
  326. * Automatically configure necessary settings for instant search
  327. *
  328. * @since 8.3.0
  329. */
  330. public function auto_config_search() {
  331. if ( ! current_user_can( 'edit_theme_options' ) ) {
  332. return;
  333. }
  334. // Set default result format to "expanded".
  335. update_option( Jetpack_Search_Options::OPTION_PREFIX . 'result_format', Jetpack_Search_Options::RESULT_FORMAT_EXPANDED );
  336. $this->auto_config_excluded_post_types();
  337. $this->auto_config_overlay_sidebar_widgets();
  338. $this->auto_config_woo_result_format();
  339. }
  340. /**
  341. * Automatically copy configured search widgets into the overlay sidebar
  342. *
  343. * @since 8.8.0
  344. */
  345. public function auto_config_overlay_sidebar_widgets() {
  346. global $wp_registered_sidebars;
  347. $sidebars = get_option( 'sidebars_widgets', array() );
  348. $slug = Jetpack_Search_Helpers::FILTER_WIDGET_BASE;
  349. if ( isset( $sidebars['jetpack-instant-search-sidebar'] ) ) {
  350. foreach ( (array) $sidebars['jetpack-instant-search-sidebar'] as $widget_id ) {
  351. if ( 0 === strpos( $widget_id, $slug ) ) {
  352. // Already configured.
  353. return;
  354. }
  355. }
  356. }
  357. $has_sidebar = isset( $wp_registered_sidebars['sidebar-1'] );
  358. $sidebar_id = false;
  359. $sidebar_searchbox_idx = false;
  360. if ( $has_sidebar ) {
  361. if ( empty( $sidebars['sidebar-1'] ) ) {
  362. // Adding to an empty sidebar is generally a bad idea.
  363. $has_sidebar = false;
  364. }
  365. foreach ( (array) $sidebars['sidebar-1'] as $idx => $widget_id ) {
  366. if ( 0 === strpos( $widget_id, 'search-' ) ) {
  367. $sidebar_searchbox_idx = $idx;
  368. }
  369. if ( 0 === strpos( $widget_id, $slug ) ) {
  370. $sidebar_id = (int) str_replace( Jetpack_Search_Helpers::FILTER_WIDGET_BASE . '-', '', $widget_id );
  371. break;
  372. }
  373. }
  374. }
  375. $next_id = 1;
  376. $widget_opt_name = Jetpack_Search_Helpers::get_widget_option_name();
  377. $widget_options = get_option( $widget_opt_name, array() );
  378. foreach ( $widget_options as $id => $w ) {
  379. if ( $id >= $next_id ) {
  380. $next_id = $id + 1;
  381. }
  382. }
  383. // Copy sidebar settings to overlay.
  384. if ( ( false !== $sidebar_id ) && isset( $widget_options[ $sidebar_id ] ) ) {
  385. $widget_options[ $next_id ] = $widget_options[ $sidebar_id ];
  386. update_option( $widget_opt_name, $widget_options );
  387. if ( ! isset( $sidebars['jetpack-instant-search-sidebar'] ) ) {
  388. $sidebars['jetpack-instant-search-sidebar'] = array();
  389. }
  390. array_unshift( $sidebars['jetpack-instant-search-sidebar'], Jetpack_Search_Helpers::build_widget_id( $next_id ) );
  391. update_option( 'sidebars_widgets', $sidebars );
  392. return;
  393. }
  394. // Configure overlay and sidebar (if it exists).
  395. $preconfig_opts = $this->get_preconfig_widget_options();
  396. if ( ! isset( $sidebars['jetpack-instant-search-sidebar'] ) ) {
  397. $sidebars['jetpack-instant-search-sidebar'] = array();
  398. }
  399. if ( $has_sidebar ) {
  400. $widget_options[ $next_id ] = $preconfig_opts;
  401. if ( false !== $sidebar_searchbox_idx ) {
  402. // Replace Core search box.
  403. $sidebars['sidebar-1'][ $sidebar_searchbox_idx ] = Jetpack_Search_Helpers::build_widget_id( $next_id );
  404. } else {
  405. // Add to top.
  406. array_unshift( $sidebars['sidebar-1'], Jetpack_Search_Helpers::build_widget_id( $next_id ) );
  407. }
  408. $next_id++;
  409. }
  410. $widget_options[ $next_id ] = $preconfig_opts;
  411. array_unshift( $sidebars['jetpack-instant-search-sidebar'], Jetpack_Search_Helpers::build_widget_id( $next_id ) );
  412. update_option( $widget_opt_name, $widget_options );
  413. update_option( 'sidebars_widgets', $sidebars );
  414. }
  415. /**
  416. * Autoconfig search by adding filter widgets
  417. *
  418. * @since 8.4.0
  419. *
  420. * @return array Array of config settings for search widget.
  421. */
  422. protected function get_preconfig_widget_options() {
  423. $settings = array(
  424. 'title' => '',
  425. 'filters' => array(),
  426. );
  427. $post_types = get_post_types(
  428. array(
  429. 'public' => true,
  430. '_builtin' => false,
  431. )
  432. );
  433. if ( ! empty( $post_types ) ) {
  434. $settings['filters'][] = array(
  435. 'name' => '',
  436. 'type' => 'post_type',
  437. 'count' => 5,
  438. );
  439. }
  440. // Grab a maximum of 3 taxonomies.
  441. $taxonomies = array_slice(
  442. get_taxonomies(
  443. array(
  444. 'public' => true,
  445. '_builtin' => false,
  446. )
  447. ),
  448. 0,
  449. 3
  450. );
  451. foreach ( $taxonomies as $t ) {
  452. $settings['filters'][] = array(
  453. 'name' => '',
  454. 'type' => 'taxonomy',
  455. 'taxonomy' => $t,
  456. 'count' => 5,
  457. );
  458. }
  459. $settings['filters'][] = array(
  460. 'name' => '',
  461. 'type' => 'taxonomy',
  462. 'taxonomy' => 'category',
  463. 'count' => 5,
  464. );
  465. $settings['filters'][] = array(
  466. 'name' => '',
  467. 'type' => 'taxonomy',
  468. 'taxonomy' => 'post_tag',
  469. 'count' => 5,
  470. );
  471. $settings['filters'][] = array(
  472. 'name' => '',
  473. 'type' => 'date_histogram',
  474. 'count' => 5,
  475. 'field' => 'post_date',
  476. 'interval' => 'year',
  477. );
  478. return $settings;
  479. }
  480. /**
  481. * Automatically configure post types to exclude from one of the search widgets
  482. *
  483. * @since 8.8.0
  484. */
  485. public function auto_config_excluded_post_types() {
  486. $post_types = get_post_types(
  487. array(
  488. 'exclude_from_search' => false,
  489. 'public' => true,
  490. )
  491. );
  492. $enabled_post_types = array();
  493. $widget_options = get_option( Jetpack_Search_Helpers::get_widget_option_name(), array() );
  494. // Prior to Jetpack 8.8, post types were enabled via Jetpack Search widgets rather than disabled via the Customizer.
  495. // To continue supporting post types set up in the old way, we iterate through each Jetpack Search
  496. // widget configuration and append each enabled post type to $enabled_post_types.
  497. foreach ( $widget_options as $widget_option ) {
  498. if ( isset( $widget_option['post_types'] ) && is_array( $widget_option['post_types'] ) ) {
  499. foreach ( $widget_option['post_types'] as $enabled_post_type ) {
  500. $enabled_post_types[ $enabled_post_type ] = $enabled_post_type;
  501. }
  502. }
  503. }
  504. if ( ! empty( $enabled_post_types ) ) {
  505. $post_types_to_disable = array_diff( $post_types, $enabled_post_types );
  506. update_option( Jetpack_Search_Options::OPTION_PREFIX . 'excluded_post_types', join( ',', $post_types_to_disable ) );
  507. }
  508. }
  509. /**
  510. * Automatically set result format to 'product' if WooCommerce is installed
  511. *
  512. * @since 9.6.0
  513. */
  514. public function auto_config_woo_result_format() {
  515. if ( ! method_exists( 'Jetpack', 'get_active_plugins' ) ) {
  516. return false;
  517. }
  518. // Check if WooCommerce plugin is active (based on https://docs.woocommerce.com/document/create-a-plugin/).
  519. if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', Jetpack::get_active_plugins() ), true ) ) {
  520. return false;
  521. }
  522. update_option( Jetpack_Search_Options::OPTION_PREFIX . 'result_format', Jetpack_Search_Options::RESULT_FORMAT_PRODUCT );
  523. }
  524. /**
  525. * Save sidebars_widgets option before it's migrated by WordPress
  526. *
  527. * @since 9.8.0
  528. *
  529. * @param array $old_sidebars_widgets The sidebars_widgets option value to be saved.
  530. */
  531. public function save_old_sidebars_widgets( $old_sidebars_widgets = null ) {
  532. // The function should only run before _wp_sidebars_changed which migrates the sidebars.
  533. // So when _wp_sidebars_changed doesn't exist, we should skip the logic.
  534. if ( has_filter( 'after_switch_theme', '_wp_sidebars_changed' ) !== false ) {
  535. $this->old_sidebars_widgets = ! is_null( $old_sidebars_widgets ) ? $old_sidebars_widgets : wp_get_sidebars_widgets();
  536. }
  537. }
  538. /**
  539. * Clean WordPress auto-migrated sidebar widgets from instant search sidebar before saving option sidebars_widgets
  540. *
  541. * @since 9.8.0
  542. *
  543. * @param array $sidebars_widgets The sidebars_widgets option value to be filtered.
  544. * @return array The sidebars_widgets option value to be saved
  545. */
  546. public function remove_wp_migrated_widgets( $sidebars_widgets ) {
  547. // Hook the action only when it is a theme switch i.e. $this->old_sidebars_widgets is not empty.
  548. // Ensure that the hook only runs when necessary.
  549. if (
  550. empty( $this->old_sidebars_widgets )
  551. || ! is_array( $this->old_sidebars_widgets )
  552. || ! is_array( $sidebars_widgets )
  553. || ! array_key_exists( static::JETPACK_INSTANT_SEARCH_SIDEBAR, $sidebars_widgets )
  554. || ! array_key_exists( static::JETPACK_INSTANT_SEARCH_SIDEBAR, $this->old_sidebars_widgets )
  555. // If the new Jetpack sidebar already has fewer widgets, skip execution.
  556. // Uses less than comparison for defensive programming.
  557. || count( $sidebars_widgets[ static::JETPACK_INSTANT_SEARCH_SIDEBAR ] ) <= count( $this->old_sidebars_widgets[ static::JETPACK_INSTANT_SEARCH_SIDEBAR ] )
  558. ) {
  559. return $sidebars_widgets;
  560. }
  561. $lost_widgets = array_diff( $sidebars_widgets[ static::JETPACK_INSTANT_SEARCH_SIDEBAR ], $this->old_sidebars_widgets[ static::JETPACK_INSTANT_SEARCH_SIDEBAR ] );
  562. $sidebars_widgets['wp_inactive_widgets'] = array_merge( $lost_widgets, (array) $sidebars_widgets['wp_inactive_widgets'] );
  563. $sidebars_widgets[ static::JETPACK_INSTANT_SEARCH_SIDEBAR ] = $this->old_sidebars_widgets[ static::JETPACK_INSTANT_SEARCH_SIDEBAR ];
  564. // Reset $this->old_sidebars_widgets because we want to run the function only once after theme switch.
  565. $this->old_sidebars_widgets = null;
  566. return $sidebars_widgets;
  567. }
  568. /**
  569. * Add current theme name as a body class for easier override
  570. *
  571. * @param string[] $classes An array of body class names.
  572. *
  573. * @return string[] The array of classes after filtering
  574. */
  575. public function add_body_class( $classes ) {
  576. $classes[] = 'jps-theme-' . get_stylesheet();
  577. return $classes;
  578. }
  579. }