class-wc-widget-layered-nav.php 16 KB

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