Completed
Push — try/composer ( 71c5da...a7c734 )
by
unknown
07:09
created

search.php ➔ jetpack_search_widget_init()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 0
dl 0
loc 7
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_Plan::supports( 'search' ) ) {
14
		return;
15
	}
16
17
	register_widget( 'Jetpack_Search_Widget' );
18
}
19
20
/**
21
 * Provides a widget to show available/selected filters on searches.
22
 *
23
 * @since 5.0.0
24
 *
25
 * @see   WP_Widget
26
 */
27
class Jetpack_Search_Widget extends WP_Widget {
28
29
	/**
30
	 * The Jetpack_Search instance.
31
	 *
32
	 * @since 5.7.0
33
	 * @var Jetpack_Search
34
	 */
35
	protected $jetpack_search;
36
37
	/**
38
	 * Number of aggregations (filters) to show by default.
39
	 *
40
	 * @since 5.8.0
41
	 * @var int
42
	 */
43
	const DEFAULT_FILTER_COUNT = 5;
44
45
	/**
46
	 * Default sort order for search results.
47
	 *
48
	 * @since 5.8.0
49
	 * @var string
50
	 */
51
	const DEFAULT_SORT = 'relevance_desc';
52
53
	/**
54
	 * Jetpack_Search_Widget constructor.
55
	 *
56
	 * @since 5.0.0
57
	 */
58
	public function __construct( $name = null ) {
59
		if ( empty( $name ) ) {
60
			$name = esc_html__( 'Search', 'jetpack' );
61
		}
62
		parent::__construct(
63
			Jetpack_Search_Helpers::FILTER_WIDGET_BASE,
64
			/** This filter is documented in modules/widgets/facebook-likebox.php */
65
			apply_filters( 'jetpack_widget_name', $name ),
66
			array(
67
				'classname'   => 'jetpack-filters widget_search',
68
				'description' => __( 'Replaces the default search with an Elasticsearch-powered search interface and filters.', 'jetpack' ),
69
			)
70
		);
71
72
		if (
73
			Jetpack_Search_Helpers::is_active_widget( $this->id ) &&
74
			! $this->is_search_active()
75
		) {
76
			$this->activate_search();
77
		}
78
79
		if ( is_admin() ) {
80
			add_action( 'sidebar_admin_setup', array( $this, 'widget_admin_setup' ) );
81
		} else {
82
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
83
		}
84
85
		add_action( 'jetpack_search_render_filters_widget_title', array( 'Jetpack_Search_Template_Tags', 'render_widget_title' ), 10, 3 );
86
		add_action( 'jetpack_search_render_filters', array( 'Jetpack_Search_Template_Tags', 'render_available_filters' ), 10, 2 );
87
	}
88
89
	/**
90
	 * Check whether search is currently active
91
	 *
92
	 * @since 6.3
93
	 */
94
	public function is_search_active() {
95
		return Jetpack::is_module_active( 'search' );
96
	}
97
98
	/**
99
	 * Activate search
100
	 *
101
	 * @since 6.3
102
	 */
103
	public function activate_search() {
104
		Jetpack::activate_module( 'search', false, false );
105
	}
106
107
108
	/**
109
	 * Enqueues the scripts and styles needed for the customizer.
110
	 *
111
	 * @since 5.7.0
112
	 */
113
	public function widget_admin_setup() {
114
		wp_enqueue_style( 'widget-jetpack-search-filters', plugins_url( 'search/css/search-widget-admin-ui.css', __FILE__ ) );
115
116
		// Required for Tracks
117
		wp_register_script(
118
			'jp-tracks',
119
			'//stats.wp.com/w.js',
120
			array(),
121
			gmdate( 'YW' ),
122
			true
123
		);
124
125
		wp_register_script(
126
			'jp-tracks-functions',
127
			plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
128
			array(),
129
			JETPACK__VERSION,
130
			false
131
		);
132
133
		wp_register_script(
134
			'jetpack-search-widget-admin',
135
			plugins_url( 'search/js/search-widget-admin.js', __FILE__ ),
136
			array( 'jquery', 'jquery-ui-sortable', 'jp-tracks', 'jp-tracks-functions' ),
137
			JETPACK__VERSION
138
		);
139
140
		wp_localize_script(
141
			'jetpack-search-widget-admin', 'jetpack_search_filter_admin', array(
142
				'defaultFilterCount' => self::DEFAULT_FILTER_COUNT,
143
				'tracksUserData'     => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
144
				'tracksEventData'    => array(
145
					'is_customizer' => (int) is_customize_preview(),
146
				),
147
				'i18n'               => array(
148
					'month'        => Jetpack_Search_Helpers::get_date_filter_type_name( 'month', false ),
149
					'year'         => Jetpack_Search_Helpers::get_date_filter_type_name( 'year', false ),
150
					'monthUpdated' => Jetpack_Search_Helpers::get_date_filter_type_name( 'month', true ),
151
					'yearUpdated'  => Jetpack_Search_Helpers::get_date_filter_type_name( 'year', true ),
152
				),
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(
241
			(array) $instance, array(
242
				'title'              => '',
243
				'search_box_enabled' => true,
244
				'user_sort_enabled'  => true,
245
				'sort'               => self::DEFAULT_SORT,
246
				'filters'            => array( array() ),
247
				'post_types'         => array(),
248
			)
249
		);
250
251
		return $instance;
252
	}
253
254
	/**
255
	 * Responsible for rendering the widget on the frontend.
256
	 *
257
	 * @since 5.0.0
258
	 *
259
	 * @param array $args     Widgets args supplied by the theme.
260
	 * @param array $instance The current widget instance.
261
	 */
262
	public function widget( $args, $instance ) {
263
		$instance = $this->jetpack_search_populate_defaults( $instance );
264
265
		$display_filters = false;
266
267
		if ( Jetpack::is_development_mode() ) {
268
			echo $args['before_widget'];
269
			?><div id="<?php echo esc_attr( $this->id ); ?>-wrapper">
270
				<div class="jetpack-search-sort-wrapper">
271
					<label>
272
						<?php esc_html_e( 'Jetpack Search not supported in Development Mode', 'jetpack' ); ?>
273
					</label>
274
				</div>
275
			</div><?php
276
			echo $args['after_widget'];
277
			return;
278
		}
279
280
		if ( is_search() ) {
281
			if ( Jetpack_Search_Helpers::should_rerun_search_in_customizer_preview() ) {
282
				Jetpack_Search::instance()->update_search_results_aggregations();
283
			}
284
285
			$filters = Jetpack_Search::instance()->get_filters();
286
287
			if ( ! Jetpack_Search_Helpers::are_filters_by_widget_disabled() && ! $this->should_display_sitewide_filters() ) {
288
				$filters = array_filter( $filters, array( $this, 'is_for_current_widget' ) );
289
			}
290
291
			if ( ! empty( $filters ) ) {
292
				$display_filters = true;
293
			}
294
		}
295
296
		if ( ! $display_filters && empty( $instance['search_box_enabled'] ) && empty( $instance['user_sort_enabled'] ) ) {
297
			return;
298
		}
299
300
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
301
302
		if ( empty( $title ) ) {
303
			$title = '';
304
		}
305
306
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
307
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
308
309
		echo $args['before_widget'];
310
		?><div id="<?php echo esc_attr( $this->id ); ?>-wrapper">
311
		<?php
312
313
		if ( ! empty( $title ) ) {
314
			/**
315
			 * Responsible for displaying the title of the Jetpack Search filters widget.
316
			 *
317
			 * @module search
318
			 *
319
			 * @since  5.7.0
320
			 *
321
			 * @param string $title                The widget's title
322
			 * @param string $args['before_title'] The HTML tag to display before the title
323
			 * @param string $args['after_title']  The HTML tag to display after the title
324
			 */
325
			do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
326
		}
327
328
		$default_sort            = isset( $instance['sort'] ) ? $instance['sort'] : self::DEFAULT_SORT;
329
		list( $orderby, $order ) = $this->sorting_to_wp_query_param( $default_sort );
330
		$current_sort            = "{$orderby}|{$order}";
331
332
		// we need to dynamically inject the sort field into the search box when the search box is enabled, and display
333
		// it separately when it's not.
334
		if ( ! empty( $instance['search_box_enabled'] ) ) {
335
			Jetpack_Search_Template_Tags::render_widget_search_form( $instance['post_types'], $orderby, $order );
336
		}
337
338
		if ( ! empty( $instance['search_box_enabled'] ) && ! empty( $instance['user_sort_enabled'] ) ) :
339
				?>
340
					<div class="jetpack-search-sort-wrapper">
341
				<label>
342
					<?php esc_html_e( 'Sort by', 'jetpack' ); ?>
343
					<select class="jetpack-search-sort">
344 View Code Duplication
						<?php foreach ( $this->get_sort_types() as $sort => $label ) { ?>
345
							<option value="<?php echo esc_attr( $sort ); ?>" <?php selected( $current_sort, $sort ); ?>>
346
								<?php echo esc_html( $label ); ?>
347
							</option>
348
						<?php } ?>
349
					</select>
350
				</label>
351
			</div>
352
		<?php
353
		endif;
354
355
		if ( $display_filters ) {
356
			/**
357
			 * Responsible for rendering filters to narrow down search results.
358
			 *
359
			 * @module search
360
			 *
361
			 * @since  5.8.0
362
			 *
363
			 * @param array $filters    The possible filters for the current query.
364
			 * @param array $post_types An array of post types to limit filtering to.
365
			 */
366
			do_action(
367
				'jetpack_search_render_filters',
368
				$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...
369
				isset( $instance['post_types'] ) ? $instance['post_types'] : null
370
			);
371
		}
372
373
		$this->maybe_render_sort_javascript( $instance, $order, $orderby );
374
375
		echo '</div>';
376
		echo $args['after_widget'];
377
	}
378
379
	/**
380
	 * Renders JavaScript for the sorting controls on the frontend.
381
	 *
382
	 * This JS is a bit complicated, but here's what it's trying to do:
383
	 * - find the search form
384
	 * - find the orderby/order fields and set default values
385
	 * - detect changes to the sort field, if it exists, and use it to set the order field values
386
	 *
387
	 * @since 5.8.0
388
	 *
389
	 * @param array  $instance The current widget instance.
390
	 * @param string $order    The order to initialize the select with.
391
	 * @param string $orderby  The orderby to initialize the select with.
392
	 */
393
	private function maybe_render_sort_javascript( $instance, $order, $orderby ) {
394
		if ( ! empty( $instance['user_sort_enabled'] ) ) :
395
		?>
396
		<script type="text/javascript">
397
				jQuery( document ).ready( function( $ ) {
398
					var orderByDefault = '<?php echo 'date' === $orderby ? 'date' : 'relevance'; ?>',
399
						orderDefault   = '<?php echo 'ASC' === $order ? 'ASC' : 'DESC'; ?>',
400
						widgetId       = decodeURIComponent( '<?php echo rawurlencode( $this->id ); ?>' ),
401
						searchQuery    = decodeURIComponent( '<?php echo rawurlencode( get_query_var( 's', '' ) ); ?>' ),
402
						isSearch       = <?php echo (int) is_search(); ?>;
403
404
					var container = $( '#' + widgetId + '-wrapper' ),
405
						form = container.find('.jetpack-search-form form'),
406
						orderBy = form.find( 'input[name=orderby]'),
407
						order = form.find( 'input[name=order]'),
408
						searchInput = form.find( 'input[name="s"]' );
409
410
					orderBy.val( orderByDefault );
411
					order.val( orderDefault );
412
413
					// Some themes don't set the search query, which results in the query being lost
414
					// when doing a sort selection. So, if the query isn't set, let's set it now. This approach
415
					// is chosen over running a regex over HTML for every search query performed.
416
					if ( isSearch && ! searchInput.val() ) {
417
						searchInput.val( searchQuery );
418
					}
419
420
					searchInput.addClass( 'show-placeholder' );
421
422
					container.find( '.jetpack-search-sort' ).change( function( event ) {
423
						var values  = event.target.value.split( '|' );
424
						orderBy.val( values[0] );
425
						order.val( values[1] );
426
427
						form.submit();
428
					});
429
				} );
430
			</script>
431
		<?php
432
		endif;
433
	}
434
435
	/**
436
	 * Convert a sort string into the separate order by and order parts.
437
	 *
438
	 * @since 5.8.0
439
	 *
440
	 * @param string $sort A sort string.
441
	 *
442
	 * @return array Order by and order.
443
	 */
444
	private function sorting_to_wp_query_param( $sort ) {
445
		$parts   = explode( '|', $sort );
446
		$orderby = isset( $_GET['orderby'] )
447
			? $_GET['orderby']
448
			: $parts[0];
449
450
		$order = isset( $_GET['order'] )
451
			? strtoupper( $_GET['order'] )
452
			: ( ( isset( $parts[1] ) && 'ASC' === strtoupper( $parts[1] ) ) ? 'ASC' : 'DESC' );
453
454
		return array( $orderby, $order );
455
	}
456
457
	/**
458
	 * Updates a particular instance of the widget. Validates and sanitizes the options.
459
	 *
460
	 * @since 5.0.0
461
	 *
462
	 * @param array $new_instance New settings for this instance as input by the user via Jetpack_Search_Widget::form().
463
	 * @param array $old_instance Old settings for this instance.
464
	 *
465
	 * @return array Settings to save.
466
	 */
467
	public function update( $new_instance, $old_instance ) {
468
		$instance = array();
469
470
		$instance['title']              = sanitize_text_field( $new_instance['title'] );
471
		$instance['search_box_enabled'] = empty( $new_instance['search_box_enabled'] ) ? '0' : '1';
472
		$instance['user_sort_enabled']  = empty( $new_instance['user_sort_enabled'] ) ? '0' : '1';
473
		$instance['sort']               = $new_instance['sort'];
474
		$instance['post_types']         = empty( $new_instance['post_types'] ) || empty( $instance['search_box_enabled'] )
475
			? array()
476
			: array_map( 'sanitize_key', $new_instance['post_types'] );
477
478
		$filters = array();
479
		if ( isset( $new_instance['filter_type'] ) ) {
480
			foreach ( (array) $new_instance['filter_type'] as $index => $type ) {
481
				$count = intval( $new_instance['num_filters'][ $index ] );
482
				$count = min( 50, $count ); // Set max boundary at 50.
483
				$count = max( 1, $count );  // Set min boundary at 1.
484
485
				switch ( $type ) {
486
					case 'taxonomy':
487
						$filters[] = array(
488
							'name'     => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
489
							'type'     => 'taxonomy',
490
							'taxonomy' => sanitize_key( $new_instance['taxonomy_type'][ $index ] ),
491
							'count'    => $count,
492
						);
493
						break;
494
					case 'post_type':
495
						$filters[] = array(
496
							'name'  => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
497
							'type'  => 'post_type',
498
							'count' => $count,
499
						);
500
						break;
501
					case 'date_histogram':
502
						$filters[] = array(
503
							'name'     => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
504
							'type'     => 'date_histogram',
505
							'count'    => $count,
506
							'field'    => sanitize_key( $new_instance['date_histogram_field'][ $index ] ),
507
							'interval' => sanitize_key( $new_instance['date_histogram_interval'][ $index ] ),
508
						);
509
						break;
510
				}
511
			}
512
		}
513
514
		if ( ! empty( $filters ) ) {
515
			$instance['filters'] = $filters;
516
		}
517
518
		return $instance;
519
	}
520
521
	/**
522
	 * Outputs the settings update form.
523
	 *
524
	 * @since 5.0.0
525
	 *
526
	 * @param array $instance Current settings.
527
	 */
528
	public function form( $instance ) {
529
		$instance = $this->jetpack_search_populate_defaults( $instance );
530
531
		$title = strip_tags( $instance['title'] );
532
533
		$hide_filters = Jetpack_Search_Helpers::are_filters_by_widget_disabled();
534
535
		$classes = sprintf(
536
			'jetpack-search-filters-widget %s %s %s',
537
			$hide_filters ? 'hide-filters' : '',
538
			$instance['search_box_enabled'] ? '' : 'hide-post-types',
539
			$this->id
540
		);
541
		?>
542
		<div class="<?php echo esc_attr( $classes ); ?>">
543
			<p>
544
				<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
545
					<?php esc_html_e( 'Title (optional):', 'jetpack' ); ?>
546
				</label>
547
				<input
548
					class="widefat"
549
					id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
550
					name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
551
					type="text"
552
					value="<?php echo esc_attr( $title ); ?>"
553
				/>
554
			</p>
555
556
			<p>
557
				<label>
558
					<input
559
						type="checkbox"
560
						class="jetpack-search-filters-widget__search-box-enabled"
561
						name="<?php echo esc_attr( $this->get_field_name( 'search_box_enabled' ) ); ?>"
562
						<?php checked( $instance['search_box_enabled'] ); ?>
563
					/>
564
					<?php esc_html_e( 'Show search box', 'jetpack' ); ?>
565
				</label>
566
			</p>
567
			<p>
568
				<label>
569
					<input
570
						type="checkbox"
571
						class="jetpack-search-filters-widget__sort-controls-enabled"
572
						name="<?php echo esc_attr( $this->get_field_name( 'user_sort_enabled' ) ); ?>"
573
						<?php checked( $instance['user_sort_enabled'] ); ?>
574
						<?php disabled( ! $instance['search_box_enabled'] ); ?>
575
					/>
576
					<?php esc_html_e( 'Show sort selection dropdown', 'jetpack' ); ?>
577
				</label>
578
			</p>
579
580
			<p class="jetpack-search-filters-widget__post-types-select">
581
				<label><?php esc_html_e( 'Post types to search (minimum of 1):', 'jetpack' ); ?></label>
582
				<?php foreach ( get_post_types( array( 'exclude_from_search' => false ), 'objects' ) as $post_type ) : ?>
583
					<label>
584
						<input
585
							type="checkbox"
586
							value="<?php echo esc_attr( $post_type->name ); ?>"
587
							name="<?php echo esc_attr( $this->get_field_name( 'post_types' ) ); ?>[]"
588
							<?php checked( empty( $instance['post_types'] ) || in_array( $post_type->name, $instance['post_types'] ) ); ?>
589
						/>&nbsp;
590
						<?php echo esc_html( $post_type->label ); ?>
591
					</label>
592
				<?php endforeach; ?>
593
			</p>
594
595
			<p>
596
				<label>
597
					<?php esc_html_e( 'Default sort order:', 'jetpack' ); ?>
598
					<select
599
						name="<?php echo esc_attr( $this->get_field_name( 'sort' ) ); ?>"
600
						class="widefat jetpack-search-filters-widget__sort-order">
601 View Code Duplication
						<?php foreach ( $this->get_sort_types() as $sort_type => $label ) { ?>
602
							<option value="<?php echo esc_attr( $sort_type ); ?>" <?php selected( $instance['sort'], $sort_type ); ?>>
603
								<?php echo esc_html( $label ); ?>
604
							</option>
605
						<?php } ?>
606
					</select>
607
				</label>
608
			</p>
609
610
			<?php if ( ! $hide_filters ) : ?>
611
				<script class="jetpack-search-filters-widget__filter-template" type="text/template">
612
					<?php echo $this->render_widget_edit_filter( array(), true ); ?>
613
				</script>
614
				<div class="jetpack-search-filters-widget__filters">
615
					<?php foreach ( (array) $instance['filters'] as $filter ) : ?>
616
						<?php $this->render_widget_edit_filter( $filter ); ?>
617
					<?php endforeach; ?>
618
				</div>
619
				<p class="jetpack-search-filters-widget__add-filter-wrapper">
620
					<a class="button jetpack-search-filters-widget__add-filter" href="#">
621
						<?php esc_html_e( 'Add a filter', 'jetpack' ); ?>
622
					</a>
623
				</p>
624
				<noscript>
625
					<p class="jetpack-search-filters-help">
626
						<?php echo esc_html_e( 'Adding filters requires JavaScript!', 'jetpack' ); ?>
627
					</p>
628
				</noscript>
629
				<?php if ( is_customize_preview() ) : ?>
630
					<p class="jetpack-search-filters-help">
631
						<a href="https://jetpack.com/support/search/#filters-not-showing-up" target="_blank">
632
							<?php esc_html_e( "Why aren't my filters appearing?", 'jetpack' ); ?>
633
						</a>
634
					</p>
635
				<?php endif; ?>
636
			<?php endif; ?>
637
		</div>
638
		<?php
639
	}
640
641
	/**
642
	 * We need to render HTML in two formats: an Underscore template (client-side)
643
	 * and native PHP (server-side). This helper function allows for easy rendering
644
	 * of attributes in both formats.
645
	 *
646
	 * @since 5.8.0
647
	 *
648
	 * @param string $name        Attribute name.
649
	 * @param string $value       Attribute value.
650
	 * @param bool   $is_template Whether this is for an Underscore template or not.
651
	 */
652
	private function render_widget_attr( $name, $value, $is_template ) {
653
		echo $is_template ? "<%= $name %>" : esc_attr( $value );
654
	}
655
656
	/**
657
	 * We need to render HTML in two formats: an Underscore template (client-size)
658
	 * and native PHP (server-side). This helper function allows for easy rendering
659
	 * of the "selected" attribute in both formats.
660
	 *
661
	 * @since 5.8.0
662
	 *
663
	 * @param string $name        Attribute name.
664
	 * @param string $value       Attribute value.
665
	 * @param string $compare     Value to compare to the attribute value to decide if it should be selected.
666
	 * @param bool   $is_template Whether this is for an Underscore template or not.
667
	 */
668
	private function render_widget_option_selected( $name, $value, $compare, $is_template ) {
669
		$compare_js = rawurlencode( $compare );
670
		echo $is_template ? "<%= decodeURIComponent( '$compare_js' ) === $name ? 'selected=\"selected\"' : '' %>" : selected( $value, $compare );
671
	}
672
673
	/**
674
	 * Responsible for rendering a single filter in the customizer or the widget administration screen in wp-admin.
675
	 *
676
	 * We use this method for two purposes - rendering the fields server-side, and also rendering a script template for Underscore.
677
	 *
678
	 * @since 5.7.0
679
	 *
680
	 * @param array $filter      The filter to render.
681
	 * @param bool  $is_template Whether this is for an Underscore template or not.
682
	 */
683
	public function render_widget_edit_filter( $filter, $is_template = false ) {
684
		$args = wp_parse_args(
685
			$filter, array(
686
				'name'      => '',
687
				'type'      => 'taxonomy',
688
				'taxonomy'  => '',
689
				'post_type' => '',
690
				'field'     => '',
691
				'interval'  => '',
692
				'count'     => self::DEFAULT_FILTER_COUNT,
693
			)
694
		);
695
696
		$args['name_placeholder'] = Jetpack_Search_Helpers::generate_widget_filter_name( $args );
697
698
		?>
699
		<div class="jetpack-search-filters-widget__filter is-<?php $this->render_widget_attr( 'type', $args['type'], $is_template ); ?>">
700
			<p class="jetpack-search-filters-widget__type-select">
701
				<label>
702
					<?php esc_html_e( 'Filter Type:', 'jetpack' ); ?>
703
					<select name="<?php echo esc_attr( $this->get_field_name( 'filter_type' ) ); ?>[]" class="widefat filter-select">
704
						<option value="taxonomy" <?php $this->render_widget_option_selected( 'type', $args['type'], 'taxonomy', $is_template ); ?>>
705
							<?php esc_html_e( 'Taxonomy', 'jetpack' ); ?>
706
						</option>
707
						<option value="post_type" <?php $this->render_widget_option_selected( 'type', $args['type'], 'post_type', $is_template ); ?>>
708
							<?php esc_html_e( 'Post Type', 'jetpack' ); ?>
709
						</option>
710
						<option value="date_histogram" <?php $this->render_widget_option_selected( 'type', $args['type'], 'date_histogram', $is_template ); ?>>
711
							<?php esc_html_e( 'Date', 'jetpack' ); ?>
712
						</option>
713
					</select>
714
				</label>
715
			</p>
716
717
			<p class="jetpack-search-filters-widget__taxonomy-select">
718
				<label>
719
					<?php
720
						esc_html_e( 'Choose a taxonomy:', 'jetpack' );
721
						$seen_taxonomy_labels = array();
722
					?>
723
					<select name="<?php echo esc_attr( $this->get_field_name( 'taxonomy_type' ) ); ?>[]" class="widefat taxonomy-select">
724
						<?php foreach ( get_taxonomies( array( 'public' => true ), 'objects' ) as $taxonomy ) : ?>
725
							<option value="<?php echo esc_attr( $taxonomy->name ); ?>" <?php $this->render_widget_option_selected( 'taxonomy', $args['taxonomy'], $taxonomy->name, $is_template ); ?>>
726
								<?php
727
									$label = in_array( $taxonomy->label, $seen_taxonomy_labels )
728
										? sprintf(
729
											/* 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. */
730
											_x( '%1$s (%2$s)', 'A label for a taxonomy selector option', 'jetpack' ),
731
											$taxonomy->label,
732
											$taxonomy->name
733
										)
734
										: $taxonomy->label;
735
									echo esc_html( $label );
736
									$seen_taxonomy_labels[] = $taxonomy->label;
737
								?>
738
							</option>
739
						<?php endforeach; ?>
740
					</select>
741
				</label>
742
			</p>
743
744
			<p class="jetpack-search-filters-widget__date-histogram-select">
745
				<label>
746
					<?php esc_html_e( 'Choose a field:', 'jetpack' ); ?>
747
					<select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_field' ) ); ?>[]" class="widefat date-field-select">
748
						<option value="post_date" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date', $is_template ); ?>>
749
							<?php esc_html_e( 'Date', 'jetpack' ); ?>
750
						</option>
751
						<option value="post_date_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date_gmt', $is_template ); ?>>
752
							<?php esc_html_e( 'Date GMT', 'jetpack' ); ?>
753
						</option>
754
						<option value="post_modified" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified', $is_template ); ?>>
755
							<?php esc_html_e( 'Modified', 'jetpack' ); ?>
756
						</option>
757
						<option value="post_modified_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified_gmt', $is_template ); ?>>
758
							<?php esc_html_e( 'Modified GMT', 'jetpack' ); ?>
759
						</option>
760
					</select>
761
				</label>
762
			</p>
763
764
			<p class="jetpack-search-filters-widget__date-histogram-select">
765
				<label>
766
					<?php esc_html_e( 'Choose an interval:' ); ?>
767
					<select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_interval' ) ); ?>[]" class="widefat date-interval-select">
768
						<option value="month" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'month', $is_template ); ?>>
769
							<?php esc_html_e( 'Month', 'jetpack' ); ?>
770
						</option>
771
						<option value="year" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'year', $is_template ); ?>>
772
							<?php esc_html_e( 'Year', 'jetpack' ); ?>
773
						</option>
774
					</select>
775
				</label>
776
			</p>
777
778
			<p class="jetpack-search-filters-widget__title">
779
				<label>
780
					<?php esc_html_e( 'Title:', 'jetpack' ); ?>
781
					<input
782
						class="widefat"
783
						type="text"
784
						name="<?php echo esc_attr( $this->get_field_name( 'filter_name' ) ); ?>[]"
785
						value="<?php $this->render_widget_attr( 'name', $args['name'], $is_template ); ?>"
786
						placeholder="<?php $this->render_widget_attr( 'name_placeholder', $args['name_placeholder'], $is_template ); ?>"
787
					/>
788
				</label>
789
			</p>
790
791
			<p>
792
				<label>
793
					<?php esc_html_e( 'Maximum number of filters (1-50):', 'jetpack' ); ?>
794
					<input
795
						class="widefat filter-count"
796
						name="<?php echo esc_attr( $this->get_field_name( 'num_filters' ) ); ?>[]"
797
						type="number"
798
						value="<?php $this->render_widget_attr( 'count', $args['count'], $is_template ); ?>"
799
						min="1"
800
						max="50"
801
						step="1"
802
						required
803
					/>
804
				</label>
805
			</p>
806
807
			<p class="jetpack-search-filters-widget__controls">
808
				<a href="#" class="delete"><?php esc_html_e( 'Remove', 'jetpack' ); ?></a>
809
			</p>
810
		</div>
811
	<?php
812
	}
813
}
814