Completed
Push — unify/search-widget ( 0552f0 )
by
unknown
09:08
created

Jetpack_Search_Widget::is_search_active()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Jetpack Search: Jetpack_Search_Widget class
4
 *
5
 * @package    Jetpack
6
 * @subpackage Jetpack Search
7
 * @since      5.0.0
8
 */
9
10
add_action( 'widgets_init', 'jetpack_search_widget_init' );
11
12
function jetpack_search_widget_init() {
13
	if ( ! Jetpack::is_active() || ! Jetpack::active_plan_supports( 'search' ) ) {
14
		return;
15
	}
16
17
	require_once JETPACK__PLUGIN_DIR . 'modules/search/class.jetpack-search-helpers.php';
18
19
	register_widget( 'Jetpack_Search_Widget' );
20
}
21
22
/**
23
 * Provides a widget to show available/selected filters on searches.
24
 *
25
 * @since 5.0.0
26
 *
27
 * @see   WP_Widget
28
 */
29
class Jetpack_Search_Widget extends WP_Widget {
30
31
	/**
32
	 * The Jetpack_Search instance.
33
	 *
34
	 * @since 5.7.0
35
	 * @var Jetpack_Search
36
	 */
37
	protected $jetpack_search;
38
39
	/**
40
	 * Number of aggregations (filters) to show by default.
41
	 *
42
	 * @since 5.8.0
43
	 * @var int
44
	 */
45
	const DEFAULT_FILTER_COUNT = 5;
46
47
	/**
48
	 * Default sort order for search results.
49
	 *
50
	 * @since 5.8.0
51
	 * @var string
52
	 */
53
	const DEFAULT_SORT = 'relevance_desc';
54
55
	/**
56
	 * Jetpack_Search_Widget constructor.
57
	 *
58
	 * @since 5.0.0
59
	 */
60
	public function __construct( $name = null ) {
61
		if ( empty( $name ) ) {
62
			$name = esc_html__( 'Search', 'jetpack' );
63
		}
64
		parent::__construct(
65
			Jetpack_Search_Helpers::FILTER_WIDGET_BASE,
66
			/** This filter is documented in modules/widgets/facebook-likebox.php */
67
			apply_filters( 'jetpack_widget_name', $name ),
68
			array(
69
				'classname'   => 'jetpack-filters widget_search',
70
				'description' => __( 'Replaces the default search with an Elasticsearch-powered search interface and filters.', 'jetpack' ),
71
			)
72
		);
73
74
		if (
75
			Jetpack_Search_Helpers::is_active_widget( $this->id ) &&
76
			! $this->is_search_active()
77
		) {
78
			$this->activate_search();
79
		}
80
81
		if ( is_admin() ) {
82
			add_action( 'sidebar_admin_setup', array( $this, 'widget_admin_setup' ) );
83
		} else {
84
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
85
		}
86
87
		add_action( 'jetpack_search_render_filters_widget_title', array( 'Jetpack_Search_Template_Tags', 'render_widget_title' ), 10, 3 );
88
		add_action( 'jetpack_search_render_filters', array( 'Jetpack_Search_Template_Tags', 'render_available_filters' ), 10, 2 );
89
	}
90
91
	/**
92
	 * Check whether search is currently active
93
	 *
94
	 * @since 6.3
95
	 */
96
	public function is_search_active() {
97
		return Jetpack::is_module_active( 'search' );
98
	}
99
100
	/**
101
	 * Activate search
102
	 *
103
	 * @since 6.3
104
	 */
105
	public function activate_search() {
106
		Jetpack::activate_module( 'search', false, false );
107
	}
108
109
110
	/**
111
	 * Enqueues the scripts and styles needed for the customizer.
112
	 *
113
	 * @since 5.7.0
114
	 */
115
	public function widget_admin_setup() {
116
		wp_enqueue_style( 'widget-jetpack-search-filters', plugins_url( 'search/css/search-widget-admin-ui.css', __FILE__ ) );
117
118
		// Required for Tracks
119
		wp_register_script(
120
			'jp-tracks',
121
			'//stats.wp.com/w.js',
122
			array(),
123
			gmdate( 'YW' ),
124
			true
125
		);
126
127
		wp_register_script(
128
			'jp-tracks-functions',
129
			plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
130
			array(),
131
			JETPACK__VERSION,
132
			false
133
		);
134
135
		wp_register_script(
136
			'jetpack-search-widget-admin',
137
			plugins_url( 'search/js/search-widget-admin.js', __FILE__ ),
138
			array( 'jquery', 'jquery-ui-sortable', 'jp-tracks', 'jp-tracks-functions' ),
139
			JETPACK__VERSION
140
		);
141
142
		wp_localize_script( 'jetpack-search-widget-admin', 'jetpack_search_filter_admin', array(
143
			'defaultFilterCount' => self::DEFAULT_FILTER_COUNT,
144
			'tracksUserData'     => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
145
			'tracksEventData'    => array(
146
				'is_customizer' => ( function_exists( 'is_customize_preview' ) && is_customize_preview() ) ? 1 : 0,
147
			),
148
			'i18n'               => array(
149
				'month'        => Jetpack_Search_Helpers::get_date_filter_type_name( 'month', false ),
150
				'year'         => Jetpack_Search_Helpers::get_date_filter_type_name( 'year', false ),
151
				'monthUpdated' => Jetpack_Search_Helpers::get_date_filter_type_name( 'month', true ),
152
				'yearUpdated'  => Jetpack_Search_Helpers::get_date_filter_type_name( 'year', true ),
153
			),
154
		) );
155
156
		wp_enqueue_script( 'jetpack-search-widget-admin' );
157
	}
158
159
	/**
160
	 * Enqueue scripts and styles for the frontend.
161
	 *
162
	 * @since 5.8.0
163
	 */
164
	public function enqueue_frontend_scripts() {
165
		if ( ! is_active_widget( false, false, $this->id_base, true ) ) {
166
			return;
167
		}
168
169
		wp_enqueue_script(
170
			'jetpack-search-widget',
171
			plugins_url( 'search/js/search-widget.js', __FILE__ ),
172
			array( 'jquery' ),
173
			JETPACK__VERSION,
174
			true
175
		);
176
177
		wp_enqueue_style( 'jetpack-search-widget', plugins_url( 'search/css/search-widget-frontend.css', __FILE__ ) );
178
	}
179
180
	/**
181
	 * Get the list of valid sort types/orders.
182
	 *
183
	 * @since 5.8.0
184
	 *
185
	 * @return array The sort orders.
186
	 */
187
	private function get_sort_types() {
188
		return array(
189
			'relevance|DESC' => is_admin() ? esc_html__( 'Relevance (recommended)', 'jetpack' ) : esc_html__( 'Relevance', 'jetpack' ),
190
			'date|DESC'      => esc_html__( 'Newest first', 'jetpack' ),
191
			'date|ASC'       => esc_html__( 'Oldest first', 'jetpack' )
192
		);
193
	}
194
195
	/**
196
	 * Callback for an array_filter() call in order to only get filters for the current widget.
197
	 *
198
	 * @see   Jetpack_Search_Widget::widget()
199
	 *
200
	 * @since 5.7.0
201
	 *
202
	 * @param array $item Filter item.
203
	 *
204
	 * @return bool Whether the current filter item is for the current widget.
205
	 */
206
	function is_for_current_widget( $item ) {
207
		return isset( $item['widget_id'] ) && $this->id == $item['widget_id'];
208
	}
209
210
	/**
211
	 * This method returns a boolean for whether the widget should show site-wide filters for the site.
212
	 *
213
	 * This is meant to provide backwards-compatibility for VIP, and other professional plan users, that manually
214
	 * configured filters via `Jetpack_Search::set_filters()`.
215
	 *
216
	 * @since 5.7.0
217
	 *
218
	 * @return bool Whether the widget should display site-wide filters or not.
219
	 */
220
	public function should_display_sitewide_filters() {
221
		$filter_widgets = get_option( 'widget_jetpack-search-filters' );
222
223
		// This shouldn't be empty, but just for sanity
224
		if ( empty( $filter_widgets ) ) {
225
			return false;
226
		}
227
228
		// If any widget has any filters, return false
229
		foreach ( $filter_widgets as $number => $widget ) {
230
			$widget_id = sprintf( '%s-%d', $this->id_base, $number );
231
			if ( ! empty( $widget['filters'] ) && is_active_widget( false, $widget_id, $this->id_base ) ) {
232
				return false;
233
			}
234
		}
235
236
		return true;
237
	}
238
239
	public function jetpack_search_populate_defaults( $instance ) {
240
		$instance = wp_parse_args( (array) $instance, array(
241
			'title'              => '',
242
			'search_box_enabled' => true,
243
			'user_sort_enabled'  => true,
244
			'sort'               => self::DEFAULT_SORT,
245
			'filters'            => array( array() ),
246
		) );
247
248
		return $instance;
249
	}
250
251
	/**
252
	 * Responsible for rendering the widget on the frontend.
253
	 *
254
	 * @since 5.0.0
255
	 *
256
	 * @param array $args     Widgets args supplied by the theme.
257
	 * @param array $instance The current widget instance.
258
	 */
259
	public function widget( $args, $instance ) {
260
		$instance = $this->jetpack_search_populate_defaults( $instance );
261
262
		$display_filters = false;
263
264
		if ( is_search() ) {
265
			if ( Jetpack_Search_Helpers::should_rerun_search_in_customizer_preview() ) {
266
				Jetpack_Search::instance()->update_search_results_aggregations();
267
			}
268
269
			$filters = Jetpack_Search::instance()->get_filters();
270
271
			if ( ! Jetpack_Search_Helpers::are_filters_by_widget_disabled() && ! $this->should_display_sitewide_filters() ) {
272
				$filters = array_filter( $filters, array( $this, 'is_for_current_widget' ) );
273
			}
274
275
			if ( ! empty( $filters ) ) {
276
				$display_filters = true;
277
			}
278
		}
279
280
		if ( ! $display_filters && empty( $instance['search_box_enabled'] ) && empty( $instance['user_sort_enabled'] ) ) {
281
			return;
282
		}
283
284
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
285
286
		if ( empty( $title ) ) {
287
			$title = '';
288
		}
289
290
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
291
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
292
293
		echo $args['before_widget'];
294
		?><div id="<?php echo esc_attr( $this->id ); ?>-wrapper"><?php
295
296
		if ( ! empty( $title ) ) {
297
			/**
298
			 * Responsible for displaying the title of the Jetpack Search filters widget.
299
			 *
300
			 * @module search
301
			 *
302
			 * @since  5.7.0
303
			 *
304
			 * @param string $title                The widget's title
305
			 * @param string $args['before_title'] The HTML tag to display before the title
306
			 * @param string $args['after_title']  The HTML tag to display after the title
307
			 */
308
			do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
309
		}
310
311
		$default_sort = isset( $instance['sort'] ) ? $instance['sort'] : self::DEFAULT_SORT;
312
		list( $orderby, $order ) = $this->sorting_to_wp_query_param( $default_sort );
313
		$current_sort = "{$orderby}|{$order}";
314
315
		// we need to dynamically inject the sort field into the search box when the search box is enabled, and display
316
		// it separately when it's not.
317
		if ( ! empty( $instance['search_box_enabled'] ) ) {
318
			Jetpack_Search_Template_Tags::render_widget_search_form( $instance['post_types'], $orderby, $order );
319
		}
320
321
		if ( ! empty( $instance['search_box_enabled'] ) && ! empty( $instance['user_sort_enabled'] ) ): ?>
322
			<div class="jetpack-search-sort-wrapper">
323
				<label>
324
					<?php esc_html_e( 'Sort by', 'jetpack' ); ?>
325
					<select class="jetpack-search-sort">
326 View Code Duplication
						<?php foreach ( $this->get_sort_types() as $sort => $label ) { ?>
327
							<option value="<?php echo esc_attr( $sort ); ?>" <?php selected( $current_sort, $sort ); ?>>
328
								<?php echo esc_html( $label ); ?>
329
							</option>
330
						<?php } ?>
331
					</select>
332
				</label>
333
			</div>
334
		<?php endif;
335
336
		if ( $display_filters ) {
337
			/**
338
			 * Responsible for rendering filters to narrow down search results.
339
			 *
340
			 * @module search
341
			 *
342
			 * @since  5.8.0
343
			 *
344
			 * @param array $filters    The possible filters for the current query.
345
			 * @param array $post_types An array of post types to limit filtering to.
346
			 */
347
			do_action(
348
				'jetpack_search_render_filters',
349
				$filters,
0 ignored issues
show
Bug introduced by
The variable $filters does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
350
				isset( $instance['post_types'] ) ? $instance['post_types'] : null
351
			);
352
		}
353
354
		$this->maybe_render_sort_javascript( $instance, $order, $orderby );
355
356
		echo "</div>";
357
		echo $args['after_widget'];
358
	}
359
360
	/**
361
	 * Renders JavaScript for the sorting controls on the frontend.
362
	 *
363
	 * This JS is a bit complicated, but here's what it's trying to do:
364
	 * - find the search form
365
	 * - find the orderby/order fields and set default values
366
	 * - detect changes to the sort field, if it exists, and use it to set the order field values
367
	 *
368
	 * @since 5.8.0
369
	 *
370
	 * @param array  $instance The current widget instance.
371
	 * @param string $order    The order to initialize the select with.
372
	 * @param string $orderby  The orderby to initialize the select with.
373
	 */
374
	private function maybe_render_sort_javascript( $instance, $order, $orderby ) {
375
		if ( ! empty( $instance['user_sort_enabled'] ) ) :
376
		?>
377
		<script type="text/javascript">
378
				jQuery( document ).ready( function( $ ) {
379
					var orderByDefault = <?php echo wp_json_encode( $orderby ); ?>,
380
						orderDefault   = <?php echo wp_json_encode( $order ); ?>,
381
						widgetId       = <?php echo wp_json_encode( $this->id ); ?>,
382
						searchQuery    = <?php echo wp_json_encode( get_query_var( 's', '' ) ); ?>,
383
						isSearch       = <?php echo wp_json_encode( is_search() ); ?>;
384
385
					var container = $( '#' + widgetId + '-wrapper' ),
386
						form = container.find('.jetpack-search-form form'),
387
						orderBy = form.find( 'input[name=orderby]'),
388
						order = form.find( 'input[name=order]'),
389
						searchInput = form.find( 'input[name="s"]' );
390
391
					orderBy.val( orderByDefault );
392
					order.val( orderDefault );
393
394
					// Some themes don't set the search query, which results in the query being lost
395
					// when doing a sort selection. So, if the query isn't set, let's set it now. This approach
396
					// is chosen over running a regex over HTML for every search query performed.
397
					if ( isSearch && ! searchInput.val() ) {
398
						searchInput.val( searchQuery );
399
					}
400
401
					searchInput.addClass( 'show-placeholder' );
402
403
					container.find( '.jetpack-search-sort' ).change( function( event ) {
404
						var values  = event.target.value.split( '|' );
405
						orderBy.val( values[0] );
406
						order.val( values[1] );
407
408
						form.submit();
409
					});
410
				} );
411
			</script>
412
		<?php
413
		endif;
414
	}
415
416
	/**
417
	 * Convert a sort string into the separate order by and order parts.
418
	 *
419
	 * @since 5.8.0
420
	 *
421
	 * @param string $sort A sort string.
422
	 *
423
	 * @return array Order by and order.
424
	 */
425
	private function sorting_to_wp_query_param( $sort ) {
426
		$parts   = explode( '|', $sort );
427
		$orderby = isset( $_GET['orderby'] )
428
			? $_GET['orderby']
429
			: $parts[0];
430
431
		$order = isset( $_GET['order'] )
432
			? strtoupper( $_GET['order'] )
433
			: ( ( isset( $parts[1] ) && 'ASC' === strtoupper( $parts[1] ) ) ? 'ASC' : 'DESC' );
434
435
		return array( $orderby, $order );
436
	}
437
438
	/**
439
	 * Updates a particular instance of the widget. Validates and sanitizes the options.
440
	 *
441
	 * @since 5.0.0
442
	 *
443
	 * @param array $new_instance New settings for this instance as input by the user via Jetpack_Search_Widget::form().
444
	 * @param array $old_instance Old settings for this instance.
445
	 *
446
	 * @return array Settings to save.
447
	 */
448
	public function update( $new_instance, $old_instance ) {
449
		$instance = array();
450
451
		$instance['title']              = sanitize_text_field( $new_instance['title'] );
452
		$instance['search_box_enabled'] = empty( $new_instance['search_box_enabled'] ) ? '0' : '1';
453
		$instance['user_sort_enabled']  = empty( $new_instance['user_sort_enabled'] ) ? '0' : '1';
454
		$instance['sort']               = $new_instance['sort'];
455
		$instance['post_types']         = empty( $new_instance['post_types'] ) || empty( $instance['search_box_enabled'] )
456
			? array()
457
			: array_map( 'sanitize_key', $new_instance['post_types'] );
458
459
		$filters = array();
460
		if ( isset( $new_instance['filter_type'] ) ) {
461
			foreach ( (array) $new_instance['filter_type'] as $index => $type ) {
462
				$count = intval( $new_instance['num_filters'][ $index ] );
463
				$count = min( 50, $count ); // Set max boundary at 50.
464
				$count = max( 1, $count );  // Set min boundary at 1.
465
466
				switch ( $type ) {
467
					case 'taxonomy':
468
						$filters[] = array(
469
							'name'     => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
470
							'type'     => 'taxonomy',
471
							'taxonomy' => sanitize_key( $new_instance['taxonomy_type'][ $index ] ),
472
							'count'    => $count,
473
						);
474
						break;
475
					case 'post_type':
476
						$filters[] = array(
477
							'name'  => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
478
							'type'  => 'post_type',
479
							'count' => $count,
480
						);
481
						break;
482
					case 'date_histogram':
483
						$filters[] = array(
484
							'name'     => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
485
							'type'     => 'date_histogram',
486
							'count'    => $count,
487
							'field'    => sanitize_key( $new_instance['date_histogram_field'][ $index ] ),
488
							'interval' => sanitize_key( $new_instance['date_histogram_interval'][ $index ] ),
489
						);
490
						break;
491
				}
492
			}
493
		}
494
495
		if ( ! empty( $filters ) ) {
496
			$instance['filters'] = $filters;
497
		}
498
499
		return $instance;
500
	}
501
502
	/**
503
	 * Outputs the settings update form.
504
	 *
505
	 * @since 5.0.0
506
	 *
507
	 * @param array $instance Current settings.
508
	 */
509
	public function form( $instance ) {
510
		$instance = $this->jetpack_search_populate_defaults( $instance );
511
512
		$title = strip_tags( $instance['title'] );
513
514
		$hide_filters = Jetpack_Search_Helpers::are_filters_by_widget_disabled();
515
516
		$classes = sprintf(
517
			'jetpack-search-filters-widget %s %s %s',
518
			$hide_filters ? 'hide-filters' : '',
519
			$instance['search_box_enabled'] ? '' : 'hide-post-types',
520
			$this->id
521
		);
522
		?>
523
		<div class="<?php echo esc_attr( $classes ); ?>">
524
			<p>
525
				<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
526
					<?php esc_html_e( 'Title (optional):', 'jetpack' ); ?>
527
				</label>
528
				<input
529
					class="widefat"
530
					id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
531
					name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
532
					type="text"
533
					value="<?php echo esc_attr( $title ); ?>"
534
				/>
535
			</p>
536
537
			<p>
538
				<label>
539
					<input
540
						type="checkbox"
541
						class="jetpack-search-filters-widget__search-box-enabled"
542
						name="<?php echo esc_attr( $this->get_field_name( 'search_box_enabled' ) ); ?>"
543
						<?php checked( $instance['search_box_enabled'] ); ?>
544
					/>
545
					<?php esc_html_e( 'Show search box', 'jetpack' ); ?>
546
				</label>
547
			</p>
548
			<p>
549
				<label>
550
					<input
551
						type="checkbox"
552
						class="jetpack-search-filters-widget__sort-controls-enabled"
553
						name="<?php echo esc_attr( $this->get_field_name( 'user_sort_enabled' ) ); ?>"
554
						<?php checked( $instance['user_sort_enabled'] ); ?>
555
						<?php disabled( ! $instance['search_box_enabled'] ); ?>
556
					/>
557
					<?php esc_html_e( 'Show sort selection dropdown', 'jetpack' ); ?>
558
				</label>
559
			</p>
560
561
			<p class="jetpack-search-filters-widget__post-types-select">
562
				<label><?php esc_html_e( 'Post types to search (minimum of 1):', 'jetpack' ); ?></label>
563
				<?php foreach ( get_post_types( array( 'exclude_from_search' => false ), 'objects' ) as $post_type ) : ?>
564
					<label>
565
						<input
566
							type="checkbox"
567
							value="<?php echo esc_attr( $post_type->name ); ?>"
568
							name="<?php echo esc_attr( $this->get_field_name( 'post_types' ) ); ?>[]"
569
							<?php checked( empty( $instance['post_types'] ) || in_array( $post_type->name, $instance['post_types'] ) ); ?>
570
						/>&nbsp;
571
						<?php echo esc_html( $post_type->label ); ?>
572
					</label>
573
				<?php endforeach; ?>
574
			</p>
575
576
			<p>
577
				<label>
578
					<?php esc_html_e( 'Default sort order:', 'jetpack' ); ?>
579
					<select
580
						name="<?php echo esc_attr( $this->get_field_name( 'sort' ) ); ?>"
581
						class="widefat jetpack-search-filters-widget__sort-order">
582 View Code Duplication
						<?php foreach ( $this->get_sort_types() as $sort_type => $label ) { ?>
583
							<option value="<?php echo esc_attr( $sort_type ); ?>" <?php selected( $instance['sort'], $sort_type ); ?>>
584
								<?php echo esc_html( $label ); ?>
585
							</option>
586
						<?php } ?>
587
					</select>
588
				</label>
589
			</p>
590
591
			<?php if ( ! $hide_filters ): ?>
592
				<script class="jetpack-search-filters-widget__filter-template" type="text/template">
593
					<?php echo $this->render_widget_edit_filter( array(), true ); ?>
594
				</script>
595
				<div class="jetpack-search-filters-widget__filters">
596
					<?php foreach ( (array) $instance['filters'] as $filter ) : ?>
597
						<?php $this->render_widget_edit_filter( $filter ); ?>
598
					<?php endforeach; ?>
599
				</div>
600
				<p class="jetpack-search-filters-widget__add-filter-wrapper">
601
					<a class="button jetpack-search-filters-widget__add-filter" href="#">
602
						<?php esc_html_e( 'Add a filter', 'jetpack' ); ?>
603
					</a>
604
				</p>
605
				<noscript>
606
					<p class="jetpack-search-filters-help">
607
						<?php echo esc_html_e( 'Adding filters requires JavaScript!', 'jetpack' ); ?>
608
					</p>
609
				</noscript>
610
				<?php if ( is_customize_preview() ) : ?>
611
					<p class="jetpack-search-filters-help">
612
						<a href="https://jetpack.com/support/search/#filters-not-showing-up" target="_blank">
613
							<?php esc_html_e( "Why aren't my filters appearing?", 'jetpack' ); ?>
614
						</a>
615
					</p>
616
				<?php endif; ?>
617
			<?php endif; ?>
618
		</div>
619
		<?php
620
	}
621
622
	/**
623
	 * We need to render HTML in two formats: an Underscore template (client-side)
624
	 * and native PHP (server-side). This helper function allows for easy rendering
625
	 * of attributes in both formats.
626
	 *
627
	 * @since 5.8.0
628
	 *
629
	 * @param string $name        Attribute name.
630
	 * @param string $value       Attribute value.
631
	 * @param bool   $is_template Whether this is for an Underscore template or not.
632
	 */
633
	private function render_widget_attr( $name, $value, $is_template ) {
634
		echo $is_template ? "<%= $name %>" : esc_attr( $value );
635
	}
636
637
	/**
638
	 * We need to render HTML in two formats: an Underscore template (client-size)
639
	 * and native PHP (server-side). This helper function allows for easy rendering
640
	 * of the "selected" attribute in both formats.
641
	 *
642
	 * @since 5.8.0
643
	 *
644
	 * @param string $name        Attribute name.
645
	 * @param string $value       Attribute value.
646
	 * @param string $compare     Value to compare to the attribute value to decide if it should be selected.
647
	 * @param bool   $is_template Whether this is for an Underscore template or not.
648
	 */
649
	private function render_widget_option_selected( $name, $value, $compare, $is_template ) {
650
		$compare_json = wp_json_encode( $compare );
651
		echo $is_template ? "<%= $compare_json === $name ? 'selected=\"selected\"' : '' %>" : selected( $value, $compare );
652
	}
653
654
	/**
655
	 * Responsible for rendering a single filter in the customizer or the widget administration screen in wp-admin.
656
	 *
657
	 * We use this method for two purposes - rendering the fields server-side, and also rendering a script template for Underscore.
658
	 *
659
	 * @since 5.7.0
660
	 *
661
	 * @param array $filter      The filter to render.
662
	 * @param bool  $is_template Whether this is for an Underscore template or not.
663
	 */
664
	public function render_widget_edit_filter( $filter, $is_template = false ) {
665
		$args = wp_parse_args( $filter, array(
666
			'name'      => '',
667
			'type'      => 'taxonomy',
668
			'taxonomy'  => '',
669
			'post_type' => '',
670
			'field'     => '',
671
			'interval'  => '',
672
			'count'     => self::DEFAULT_FILTER_COUNT,
673
		) );
674
675
		$args['name_placeholder'] = Jetpack_Search_Helpers::generate_widget_filter_name( $args );
676
677
		?>
678
		<div class="jetpack-search-filters-widget__filter is-<?php $this->render_widget_attr( 'type', $args['type'], $is_template ); ?>">
679
			<p class="jetpack-search-filters-widget__type-select">
680
				<label>
681
					<?php esc_html_e( 'Filter Type:', 'jetpack' ); ?>
682
					<select name="<?php echo esc_attr( $this->get_field_name( 'filter_type' ) ); ?>[]" class="widefat filter-select">
683
						<option value="taxonomy" <?php $this->render_widget_option_selected( 'type', $args['type'], 'taxonomy', $is_template ); ?>>
684
							<?php esc_html_e( 'Taxonomy', 'jetpack' ); ?>
685
						</option>
686
						<option value="post_type" <?php $this->render_widget_option_selected( 'type', $args['type'], 'post_type', $is_template ); ?>>
687
							<?php esc_html_e( 'Post Type', 'jetpack' ); ?>
688
						</option>
689
						<option value="date_histogram" <?php $this->render_widget_option_selected( 'type', $args['type'], 'date_histogram', $is_template ); ?>>
690
							<?php esc_html_e( 'Date', 'jetpack' ); ?>
691
						</option>
692
					</select>
693
				</label>
694
			</p>
695
696
			<p class="jetpack-search-filters-widget__taxonomy-select">
697
				<label>
698
					<?php
699
						esc_html_e( 'Choose a taxonomy:', 'jetpack' );
700
						$seen_taxonomy_labels = array();
701
					?>
702
					<select name="<?php echo esc_attr( $this->get_field_name( 'taxonomy_type' ) ); ?>[]" class="widefat taxonomy-select">
703
						<?php foreach ( get_taxonomies( array( 'public' => true ), 'objects' ) as $taxonomy ) : ?>
704
							<option value="<?php echo esc_attr( $taxonomy->name ); ?>" <?php $this->render_widget_option_selected( 'taxonomy', $args['taxonomy'], $taxonomy->name, $is_template ); ?>>
705
								<?php
706
									$label = in_array( $taxonomy->label, $seen_taxonomy_labels )
707
										? sprintf(
708
											/* translators: %1$s is the taxonomy name, %2s is the name of its type to help distinguish between several taxonomies with the same name, e.g. category and tag. */
709
											_x( '%1$s (%2$s)', 'A label for a taxonomy selector option', 'jetpack' ),
710
											$taxonomy->label,
711
											$taxonomy->name
712
										)
713
										: $taxonomy->label;
714
									echo esc_html( $label );
715
									$seen_taxonomy_labels[] = $taxonomy->label;
716
								?>
717
							</option>
718
						<?php endforeach; ?>
719
					</select>
720
				</label>
721
			</p>
722
723
			<p class="jetpack-search-filters-widget__date-histogram-select">
724
				<label>
725
					<?php esc_html_e( 'Choose a field:', 'jetpack' ); ?>
726
					<select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_field' ) ); ?>[]" class="widefat date-field-select">
727
						<option value="post_date" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date', $is_template ); ?>>
728
							<?php esc_html_e( 'Date', 'jetpack' ); ?>
729
						</option>
730
						<option value="post_date_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date_gmt', $is_template ); ?>>
731
							<?php esc_html_e( 'Date GMT', 'jetpack' ); ?>
732
						</option>
733
						<option value="post_modified" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified', $is_template ); ?>>
734
							<?php esc_html_e( 'Modified', 'jetpack' ); ?>
735
						</option>
736
						<option value="post_modified_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified_gmt', $is_template ); ?>>
737
							<?php esc_html_e( 'Modified GMT', 'jetpack' ); ?>
738
						</option>
739
					</select>
740
				</label>
741
			</p>
742
743
			<p class="jetpack-search-filters-widget__date-histogram-select">
744
				<label>
745
					<?php esc_html_e( 'Choose an interval:' ); ?>
746
					<select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_interval' ) ); ?>[]" class="widefat date-interval-select">
747
						<option value="month" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'month', $is_template ); ?>>
748
							<?php esc_html_e( 'Month', 'jetpack' ); ?>
749
						</option>
750
						<option value="year" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'year', $is_template ); ?>>
751
							<?php esc_html_e( 'Year', 'jetpack' ); ?>
752
						</option>
753
					</select>
754
				</label>
755
			</p>
756
757
			<p class="jetpack-search-filters-widget__title">
758
				<label>
759
					<?php esc_html_e( 'Title:', 'jetpack' ); ?>
760
					<input
761
						class="widefat"
762
						type="text"
763
						name="<?php echo esc_attr( $this->get_field_name( 'filter_name' ) ); ?>[]"
764
						value="<?php $this->render_widget_attr( 'name', $args['name'], $is_template ); ?>"
765
						placeholder="<?php $this->render_widget_attr( 'name_placeholder', $args['name_placeholder'], $is_template ); ?>"
766
					/>
767
				</label>
768
			</p>
769
770
			<p>
771
				<label>
772
					<?php esc_html_e( 'Maximum number of filters (1-50):', 'jetpack' ); ?>
773
					<input
774
						class="widefat filter-count"
775
						name="<?php echo esc_attr( $this->get_field_name( 'num_filters' ) ); ?>[]"
776
						type="number"
777
						value="<?php $this->render_widget_attr( 'count', $args['count'], $is_template ); ?>"
778
						min="1"
779
						max="50"
780
						step="1"
781
						required
782
					/>
783
				</label>
784
			</p>
785
786
			<p class="jetpack-search-filters-widget__controls">
787
				<a href="#" class="delete"><?php esc_html_e( 'Remove', 'jetpack' ); ?></a>
788
			</p>
789
		</div>
790
	<?php }
791
}
792