Completed
Push — master ( effa51...64c76e )
by Mike
12:23
created

WC_Widget_Layered_Nav::get_instance_query_type()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Layered nav widget
4
 *
5
 * @package WooCommerce/Widgets
6
 * @version 2.6.0
7
 */
8
9
defined( 'ABSPATH' ) || exit;
10
11
/**
12
 * Widget layered nav class.
13
 */
14
class WC_Widget_Layered_Nav extends WC_Widget {
15
16
	/**
17
	 * Constructor.
18
	 */
19
	public function __construct() {
20
		$this->widget_cssclass    = 'woocommerce widget_layered_nav woocommerce-widget-layered-nav';
21
		$this->widget_description = __( 'Display a list of attributes to filter products in your store.', 'woocommerce' );
22
		$this->widget_id          = 'woocommerce_layered_nav';
23
		$this->widget_name        = __( 'Filter Products by Attribute', 'woocommerce' );
24
		parent::__construct();
25
	}
26
27
	/**
28
	 * Updates a particular instance of a widget.
29
	 *
30
	 * @see WP_Widget->update
31
	 *
32
	 * @param array $new_instance New Instance.
33
	 * @param array $old_instance Old Instance.
34
	 *
35
	 * @return array
36
	 */
37
	public function update( $new_instance, $old_instance ) {
38
		$this->init_settings();
39
		return parent::update( $new_instance, $old_instance );
40
	}
41
42
	/**
43
	 * Outputs the settings update form.
44
	 *
45
	 * @see WP_Widget->form
46
	 *
47
	 * @param array $instance Instance.
48
	 */
49
	public function form( $instance ) {
50
		$this->init_settings();
51
		parent::form( $instance );
52
	}
53
54
	/**
55
	 * Init settings after post types are registered.
56
	 */
57
	public function init_settings() {
58
		$attribute_array      = array();
59
		$std_attribute        = '';
60
		$attribute_taxonomies = wc_get_attribute_taxonomies();
61
62
		if ( ! empty( $attribute_taxonomies ) ) {
63
			foreach ( $attribute_taxonomies as $tax ) {
64
				if ( taxonomy_exists( wc_attribute_taxonomy_name( $tax->attribute_name ) ) ) {
65
					$attribute_array[ $tax->attribute_name ] = $tax->attribute_name;
66
				}
67
			}
68
			$std_attribute = current( $attribute_array );
69
		}
70
71
		$this->settings = array(
72
			'title'        => array(
73
				'type'  => 'text',
74
				'std'   => __( 'Filter by', 'woocommerce' ),
75
				'label' => __( 'Title', 'woocommerce' ),
76
			),
77
			'attribute'    => array(
78
				'type'    => 'select',
79
				'std'     => $std_attribute,
80
				'label'   => __( 'Attribute', 'woocommerce' ),
81
				'options' => $attribute_array,
82
			),
83
			'display_type' => array(
84
				'type'    => 'select',
85
				'std'     => 'list',
86
				'label'   => __( 'Display type', 'woocommerce' ),
87
				'options' => array(
88
					'list'     => __( 'List', 'woocommerce' ),
89
					'dropdown' => __( 'Dropdown', 'woocommerce' ),
90
				),
91
			),
92
			'query_type'   => array(
93
				'type'    => 'select',
94
				'std'     => 'and',
95
				'label'   => __( 'Query type', 'woocommerce' ),
96
				'options' => array(
97
					'and' => __( 'AND', 'woocommerce' ),
98
					'or'  => __( 'OR', 'woocommerce' ),
99
				),
100
			),
101
		);
102
	}
103
104
	/**
105
	 * Get this widgets taxonomy.
106
	 *
107
	 * @param array $instance Array of instance options.
108
	 * @return string
109
	 */
110
	protected function get_instance_taxonomy( $instance ) {
111
		if ( isset( $instance['attribute'] ) ) {
112
			return wc_attribute_taxonomy_name( $instance['attribute'] );
113
		}
114
115
		$attribute_taxonomies = wc_get_attribute_taxonomies();
116
117
		if ( ! empty( $attribute_taxonomies ) ) {
118
			foreach ( $attribute_taxonomies as $tax ) {
119
				if ( taxonomy_exists( wc_attribute_taxonomy_name( $tax->attribute_name ) ) ) {
120
					return wc_attribute_taxonomy_name( $tax->attribute_name );
121
				}
122
			}
123
		}
124
125
		return '';
126
	}
127
128
	/**
129
	 * Get this widgets query type.
130
	 *
131
	 * @param array $instance Array of instance options.
132
	 * @return string
133
	 */
134
	protected function get_instance_query_type( $instance ) {
135
		return isset( $instance['query_type'] ) ? $instance['query_type'] : 'and';
136
	}
137
138
	/**
139
	 * Get this widgets display type.
140
	 *
141
	 * @param array $instance Array of instance options.
142
	 * @return string
143
	 */
144
	protected function get_instance_display_type( $instance ) {
145
		return isset( $instance['display_type'] ) ? $instance['display_type'] : 'list';
146
	}
147
148
	/**
149
	 * Output widget.
150
	 *
151
	 * @see WP_Widget
152
	 *
153
	 * @param array $args Arguments.
154
	 * @param array $instance Instance.
155
	 */
156
	public function widget( $args, $instance ) {
157
		if ( ! is_shop() && ! is_product_taxonomy() ) {
158
			return;
159
		}
160
161
		$_chosen_attributes = WC_Query::get_layered_nav_chosen_attributes();
162
		$taxonomy           = $this->get_instance_taxonomy( $instance );
163
		$query_type         = $this->get_instance_query_type( $instance );
164
		$display_type       = $this->get_instance_display_type( $instance );
165
166
		if ( ! taxonomy_exists( $taxonomy ) ) {
167
			return;
168
		}
169
170
		$get_terms_args = array( 'hide_empty' => '1' );
171
172
		$orderby = wc_attribute_orderby( $taxonomy );
173
174
		switch ( $orderby ) {
175
			case 'name':
176
				$get_terms_args['orderby']    = 'name';
177
				$get_terms_args['menu_order'] = false;
178
				break;
179
			case 'id':
180
				$get_terms_args['orderby']    = 'id';
181
				$get_terms_args['order']      = 'ASC';
182
				$get_terms_args['menu_order'] = false;
183
				break;
184
			case 'menu_order':
185
				$get_terms_args['menu_order'] = 'ASC';
186
				break;
187
		}
188
189
		$terms = get_terms( $taxonomy, $get_terms_args );
190
191
		if ( 0 === count( $terms ) ) {
192
			return;
193
		}
194
195 View Code Duplication
		switch ( $orderby ) {
196
			case 'name_num':
197
				usort( $terms, '_wc_get_product_terms_name_num_usort_callback' );
198
				break;
199
			case 'parent':
200
				usort( $terms, '_wc_get_product_terms_parent_usort_callback' );
201
				break;
202
		}
203
204
		ob_start();
205
206
		$this->widget_start( $args, $instance );
207
208
		if ( 'dropdown' === $display_type ) {
209
			wp_enqueue_script( 'selectWoo' );
210
			wp_enqueue_style( 'select2' );
211
			$found = $this->layered_nav_dropdown( $terms, $taxonomy, $query_type );
212
		} else {
213
			$found = $this->layered_nav_list( $terms, $taxonomy, $query_type );
214
		}
215
216
		$this->widget_end( $args );
217
218
		// Force found when option is selected - do not force found on taxonomy attributes.
219
		if ( ! is_tax() && is_array( $_chosen_attributes ) && array_key_exists( $taxonomy, $_chosen_attributes ) ) {
220
			$found = true;
221
		}
222
223
		if ( ! $found ) {
224
			ob_end_clean();
225
		} else {
226
			echo ob_get_clean(); // @codingStandardsIgnoreLine
227
		}
228
	}
229
230
	/**
231
	 * Return the currently viewed taxonomy name.
232
	 *
233
	 * @return string
234
	 */
235
	protected function get_current_taxonomy() {
236
		return is_tax() ? get_queried_object()->taxonomy : '';
237
	}
238
239
	/**
240
	 * Return the currently viewed term ID.
241
	 *
242
	 * @return int
243
	 */
244
	protected function get_current_term_id() {
245
		return absint( is_tax() ? get_queried_object()->term_id : 0 );
246
	}
247
248
	/**
249
	 * Return the currently viewed term slug.
250
	 *
251
	 * @return int
252
	 */
253
	protected function get_current_term_slug() {
254
		return absint( is_tax() ? get_queried_object()->slug : 0 );
255
	}
256
257
	/**
258
	 * Show dropdown layered nav.
259
	 *
260
	 * @param  array  $terms Terms.
261
	 * @param  string $taxonomy Taxonomy.
262
	 * @param  string $query_type Query Type.
263
	 * @return bool Will nav display?
264
	 */
265
	protected function layered_nav_dropdown( $terms, $taxonomy, $query_type ) {
266
		global $wp;
267
		$found = false;
268
269
		if ( $taxonomy !== $this->get_current_taxonomy() ) {
270
			$term_counts          = $this->get_filtered_term_product_counts( wp_list_pluck( $terms, 'term_id' ), $taxonomy, $query_type );
271
			$_chosen_attributes   = WC_Query::get_layered_nav_chosen_attributes();
272
			$taxonomy_filter_name = wc_attribute_taxonomy_slug( $taxonomy );
273
			$taxonomy_label       = wc_attribute_label( $taxonomy );
274
275
			/* translators: %s: taxonomy name */
276
			$any_label      = apply_filters( 'woocommerce_layered_nav_any_label', sprintf( __( 'Any %s', 'woocommerce' ), $taxonomy_label ), $taxonomy_label, $taxonomy );
277
			$multiple       = 'or' === $query_type;
278
			$current_values = isset( $_chosen_attributes[ $taxonomy ]['terms'] ) ? $_chosen_attributes[ $taxonomy ]['terms'] : array();
279
280 View Code Duplication
			if ( '' === get_option( 'permalink_structure' ) ) {
281
				$form_action = remove_query_arg( array( 'page', 'paged' ), add_query_arg( $wp->query_string, '', home_url( $wp->request ) ) );
282
			} else {
283
				$form_action = preg_replace( '%\/page/[0-9]+%', '', home_url( trailingslashit( $wp->request ) ) );
284
			}
285
286
			echo '<form method="get" action="' . esc_url( $form_action ) . '" class="woocommerce-widget-layered-nav-dropdown">';
287
			echo '<select class="woocommerce-widget-layered-nav-dropdown dropdown_layered_nav_' . esc_attr( $taxonomy_filter_name ) . '"' . ( $multiple ? 'multiple="multiple"' : '' ) . '>';
288
			echo '<option value="">' . esc_html( $any_label ) . '</option>';
289
290
			foreach ( $terms as $term ) {
291
292
				// If on a term page, skip that term in widget list.
293
				if ( $term->term_id === $this->get_current_term_id() ) {
294
					continue;
295
				}
296
297
				// Get count based on current view.
298
				$option_is_set = in_array( $term->slug, $current_values, true );
299
				$count         = isset( $term_counts[ $term->term_id ] ) ? $term_counts[ $term->term_id ] : 0;
300
301
				// Only show options with count > 0.
302 View Code Duplication
				if ( 0 < $count ) {
303
					$found = true;
304
				} elseif ( 0 === $count && ! $option_is_set ) {
305
					continue;
306
				}
307
308
				echo '<option value="' . esc_attr( urldecode( $term->slug ) ) . '" ' . selected( $option_is_set, true, false ) . '>' . esc_html( $term->name ) . '</option>';
309
			}
310
311
			echo '</select>';
312
313
			if ( $multiple ) {
314
				echo '<button class="woocommerce-widget-layered-nav-dropdown__submit" type="submit" value="' . esc_attr__( 'Apply', 'woocommerce' ) . '">' . esc_html__( 'Apply', 'woocommerce' ) . '</button>';
315
			}
316
317
			if ( 'or' === $query_type ) {
318
				echo '<input type="hidden" name="query_type_' . esc_attr( $taxonomy_filter_name ) . '" value="or" />';
319
			}
320
321
			echo '<input type="hidden" name="filter_' . esc_attr( $taxonomy_filter_name ) . '" value="' . esc_attr( implode( ',', $current_values ) ) . '" />';
322
			echo wc_query_string_form_fields( null, array( 'filter_' . $taxonomy_filter_name, 'query_type_' . $taxonomy_filter_name ), '', true ); // @codingStandardsIgnoreLine
323
			echo '</form>';
324
325
			wc_enqueue_js(
326
				"
327
				// Update value on change.
328
				jQuery( '.dropdown_layered_nav_" . esc_js( $taxonomy_filter_name ) . "' ).change( function() {
329
					var slug = jQuery( this ).val();
330
					jQuery( ':input[name=\"filter_" . esc_js( $taxonomy_filter_name ) . "\"]' ).val( slug );
331
332
					// Submit form on change if standard dropdown.
333
					if ( ! jQuery( this ).attr( 'multiple' ) ) {
334
						jQuery( this ).closest( 'form' ).submit();
335
					}
336
				});
337
338
				// Use Select2 enhancement if possible
339
				if ( jQuery().selectWoo ) {
340
					var wc_layered_nav_select = function() {
341
						jQuery( '.dropdown_layered_nav_" . esc_js( $taxonomy_filter_name ) . "' ).selectWoo( {
342
							placeholder: " . wp_json_encode( (string) wp_specialchars_decode( $any_label ) ) . ",
343
							minimumResultsForSearch: 5,
344
							width: '100%',
345
							allowClear: " . ( $multiple ? 'false' : 'true' ) . ",
346
							language: {
347
								noResults: function() {
348
									return '" . esc_js( _x( 'No matches found', 'enhanced select', 'woocommerce' ) ) . "';
349
								}
350
							}
351
						} );
352
					};
353
					wc_layered_nav_select();
354
				}
355
			"
356
			);
357
		}
358
359
		return $found;
360
	}
361
362
	/**
363
	 * Count products within certain terms, taking the main WP query into consideration.
364
	 *
365
	 * This query allows counts to be generated based on the viewed products, not all products.
366
	 *
367
	 * @param  array  $term_ids Term IDs.
368
	 * @param  string $taxonomy Taxonomy.
369
	 * @param  string $query_type Query Type.
370
	 * @return array
371
	 */
372
	protected function get_filtered_term_product_counts( $term_ids, $taxonomy, $query_type ) {
373
		global $wpdb;
374
375
		$tax_query  = WC_Query::get_main_tax_query();
376
		$meta_query = WC_Query::get_main_meta_query();
377
378
		if ( 'or' === $query_type ) {
379
			foreach ( $tax_query as $key => $query ) {
380
				if ( is_array( $query ) && $taxonomy === $query['taxonomy'] ) {
381
					unset( $tax_query[ $key ] );
382
				}
383
			}
384
		}
385
386
		$meta_query     = new WP_Meta_Query( $meta_query );
387
		$tax_query      = new WP_Tax_Query( $tax_query );
388
		$meta_query_sql = $meta_query->get_sql( 'post', $wpdb->posts, 'ID' );
389
		$tax_query_sql  = $tax_query->get_sql( $wpdb->posts, 'ID' );
390
391
		// Generate query.
392
		$query           = array();
393
		$query['select'] = "SELECT COUNT( DISTINCT {$wpdb->posts}.ID ) as term_count, terms.term_id as term_count_id";
394
		$query['from']   = "FROM {$wpdb->posts}";
395
		$query['join']   = "
396
			INNER JOIN {$wpdb->term_relationships} AS term_relationships ON {$wpdb->posts}.ID = term_relationships.object_id
397
			INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy USING( term_taxonomy_id )
398
			INNER JOIN {$wpdb->terms} AS terms USING( term_id )
399
			" . $tax_query_sql['join'] . $meta_query_sql['join'];
400
401
		$query['where'] = "
402
			WHERE {$wpdb->posts}.post_type IN ( 'product' )
403
			AND {$wpdb->posts}.post_status = 'publish'"
404
			. $tax_query_sql['where'] . $meta_query_sql['where'] .
405
			'AND terms.term_id IN (' . implode( ',', array_map( 'absint', $term_ids ) ) . ')';
406
407
		$search = WC_Query::get_main_search_query_sql();
408
		if ( $search ) {
409
			$query['where'] .= ' AND ' . $search;
410
		}
411
412
		$query['group_by'] = 'GROUP BY terms.term_id';
413
		$query             = apply_filters( 'woocommerce_get_filtered_term_product_counts_query', $query );
414
		$query             = implode( ' ', $query );
415
416
		// We have a query - let's see if cached results of this query already exist.
417
		$query_hash = md5( $query );
418
419
		// Maybe store a transient of the count values.
420
		$cache = apply_filters( 'woocommerce_layered_nav_count_maybe_cache', true );
421
		if ( true === $cache ) {
422
			$cached_counts = (array) get_transient( 'wc_layered_nav_counts_' . sanitize_title( $taxonomy ) );
423
		} else {
424
			$cached_counts = array();
425
		}
426
427
		if ( ! isset( $cached_counts[ $query_hash ] ) ) {
428
			$results                      = $wpdb->get_results( $query, ARRAY_A ); // @codingStandardsIgnoreLine
429
			$counts                       = array_map( 'absint', wp_list_pluck( $results, 'term_count', 'term_count_id' ) );
430
			$cached_counts[ $query_hash ] = $counts;
431
			if ( true === $cache ) {
432
				set_transient( 'wc_layered_nav_counts_' . sanitize_title( $taxonomy ), $cached_counts, DAY_IN_SECONDS );
433
			}
434
		}
435
436
		return array_map( 'absint', (array) $cached_counts[ $query_hash ] );
437
	}
438
439
	/**
440
	 * Show list based layered nav.
441
	 *
442
	 * @param  array  $terms Terms.
443
	 * @param  string $taxonomy Taxonomy.
444
	 * @param  string $query_type Query Type.
445
	 * @return bool   Will nav display?
446
	 */
447
	protected function layered_nav_list( $terms, $taxonomy, $query_type ) {
448
		// List display.
449
		echo '<ul class="woocommerce-widget-layered-nav-list">';
450
451
		$term_counts        = $this->get_filtered_term_product_counts( wp_list_pluck( $terms, 'term_id' ), $taxonomy, $query_type );
452
		$_chosen_attributes = WC_Query::get_layered_nav_chosen_attributes();
453
		$found              = false;
454
455
		foreach ( $terms as $term ) {
456
			$current_values = isset( $_chosen_attributes[ $taxonomy ]['terms'] ) ? $_chosen_attributes[ $taxonomy ]['terms'] : array();
457
			$option_is_set  = in_array( $term->slug, $current_values, true );
458
			$count          = isset( $term_counts[ $term->term_id ] ) ? $term_counts[ $term->term_id ] : 0;
459
460
			// Skip the term for the current archive.
461
			if ( $this->get_current_term_id() === $term->term_id ) {
462
				continue;
463
			}
464
465
			// Only show options with count > 0.
466 View Code Duplication
			if ( 0 < $count ) {
467
				$found = true;
468
			} elseif ( 0 === $count && ! $option_is_set ) {
469
				continue;
470
			}
471
472
			$filter_name    = 'filter_' . wc_attribute_taxonomy_slug( $taxonomy );
473
			$current_filter = isset( $_GET[ $filter_name ] ) ? explode( ',', wc_clean( wp_unslash( $_GET[ $filter_name ] ) ) ) : array(); // WPCS: input var ok, CSRF ok.
0 ignored issues
show
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
474
			$current_filter = array_map( 'sanitize_title', $current_filter );
475
476
			if ( ! in_array( $term->slug, $current_filter, true ) ) {
477
				$current_filter[] = $term->slug;
478
			}
479
480
			$link = remove_query_arg( $filter_name, $this->get_current_page_url() );
481
482
			// Add current filters to URL.
483
			foreach ( $current_filter as $key => $value ) {
484
				// Exclude query arg for current term archive term.
485
				if ( $value === $this->get_current_term_slug() ) {
486
					unset( $current_filter[ $key ] );
487
				}
488
489
				// Exclude self so filter can be unset on click.
490
				if ( $option_is_set && $value === $term->slug ) {
491
					unset( $current_filter[ $key ] );
492
				}
493
			}
494
495
			if ( ! empty( $current_filter ) ) {
496
				asort( $current_filter );
497
				$link = add_query_arg( $filter_name, implode( ',', $current_filter ), $link );
498
499
				// Add Query type Arg to URL.
500
				if ( 'or' === $query_type && ! ( 1 === count( $current_filter ) && $option_is_set ) ) {
501
					$link = add_query_arg( 'query_type_' . wc_attribute_taxonomy_slug( $taxonomy ), 'or', $link );
502
				}
503
				$link = str_replace( '%2C', ',', $link );
504
			}
505
506
			if ( $count > 0 || $option_is_set ) {
507
				$link      = esc_url( apply_filters( 'woocommerce_layered_nav_link', $link, $term, $taxonomy ) );
508
				$term_html = '<a rel="nofollow" href="' . $link . '">' . esc_html( $term->name ) . '</a>';
509
			} else {
510
				$link      = false;
511
				$term_html = '<span>' . esc_html( $term->name ) . '</span>';
512
			}
513
514
			$term_html .= ' ' . apply_filters( 'woocommerce_layered_nav_count', '<span class="count">(' . absint( $count ) . ')</span>', $count, $term );
515
516
			echo '<li class="woocommerce-widget-layered-nav-list__item wc-layered-nav-term ' . ( $option_is_set ? 'woocommerce-widget-layered-nav-list__item--chosen chosen' : '' ) . '">';
517
			echo wp_kses_post( apply_filters( 'woocommerce_layered_nav_term_html', $term_html, $term, $link, $count ) );
518
			echo '</li>';
519
		}
520
521
		echo '</ul>';
522
523
		return $found;
524
	}
525
}
526