class-wc-query.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. <?php
  2. /**
  3. * Contains the query functions for WooCommerce which alter the front-end post queries and loops
  4. *
  5. * @version 3.2.0
  6. * @package WooCommerce\Classes
  7. */
  8. defined( 'ABSPATH' ) || exit;
  9. /**
  10. * WC_Query Class.
  11. */
  12. class WC_Query {
  13. /**
  14. * Query vars to add to wp.
  15. *
  16. * @var array
  17. */
  18. public $query_vars = array();
  19. /**
  20. * Reference to the main product query on the page.
  21. *
  22. * @var array
  23. */
  24. private static $product_query;
  25. /**
  26. * Stores chosen attributes.
  27. *
  28. * @var array
  29. */
  30. private static $_chosen_attributes;
  31. /**
  32. * Constructor for the query class. Hooks in methods.
  33. */
  34. public function __construct() {
  35. add_action( 'init', array( $this, 'add_endpoints' ) );
  36. if ( ! is_admin() ) {
  37. add_action( 'wp_loaded', array( $this, 'get_errors' ), 20 );
  38. add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
  39. add_action( 'parse_request', array( $this, 'parse_request' ), 0 );
  40. add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ) );
  41. add_filter( 'the_posts', array( $this, 'remove_product_query_filters' ) );
  42. add_filter( 'get_pagenum_link', array( $this, 'remove_add_to_cart_pagination' ), 10, 1 );
  43. }
  44. $this->init_query_vars();
  45. }
  46. /**
  47. * Get any errors from querystring.
  48. */
  49. public function get_errors() {
  50. $error = ! empty( $_GET['wc_error'] ) ? sanitize_text_field( wp_unslash( $_GET['wc_error'] ) ) : ''; // WPCS: input var ok, CSRF ok.
  51. if ( $error && ! wc_has_notice( $error, 'error' ) ) {
  52. wc_add_notice( $error, 'error' );
  53. }
  54. }
  55. /**
  56. * Init query vars by loading options.
  57. */
  58. public function init_query_vars() {
  59. // Query vars to add to WP.
  60. $this->query_vars = array(
  61. // Checkout actions.
  62. 'order-pay' => get_option( 'woocommerce_checkout_pay_endpoint', 'order-pay' ),
  63. 'order-received' => get_option( 'woocommerce_checkout_order_received_endpoint', 'order-received' ),
  64. // My account actions.
  65. 'orders' => get_option( 'woocommerce_myaccount_orders_endpoint', 'orders' ),
  66. 'view-order' => get_option( 'woocommerce_myaccount_view_order_endpoint', 'view-order' ),
  67. 'downloads' => get_option( 'woocommerce_myaccount_downloads_endpoint', 'downloads' ),
  68. 'edit-account' => get_option( 'woocommerce_myaccount_edit_account_endpoint', 'edit-account' ),
  69. 'edit-address' => get_option( 'woocommerce_myaccount_edit_address_endpoint', 'edit-address' ),
  70. 'payment-methods' => get_option( 'woocommerce_myaccount_payment_methods_endpoint', 'payment-methods' ),
  71. 'lost-password' => get_option( 'woocommerce_myaccount_lost_password_endpoint', 'lost-password' ),
  72. 'customer-logout' => get_option( 'woocommerce_logout_endpoint', 'customer-logout' ),
  73. 'add-payment-method' => get_option( 'woocommerce_myaccount_add_payment_method_endpoint', 'add-payment-method' ),
  74. 'delete-payment-method' => get_option( 'woocommerce_myaccount_delete_payment_method_endpoint', 'delete-payment-method' ),
  75. 'set-default-payment-method' => get_option( 'woocommerce_myaccount_set_default_payment_method_endpoint', 'set-default-payment-method' ),
  76. );
  77. }
  78. /**
  79. * Get page title for an endpoint.
  80. *
  81. * @param string $endpoint Endpoint key.
  82. * @return string
  83. */
  84. public function get_endpoint_title( $endpoint ) {
  85. global $wp;
  86. switch ( $endpoint ) {
  87. case 'order-pay':
  88. $title = __( 'Pay for order', 'woocommerce' );
  89. break;
  90. case 'order-received':
  91. $title = __( 'Order received', 'woocommerce' );
  92. break;
  93. case 'orders':
  94. if ( ! empty( $wp->query_vars['orders'] ) ) {
  95. /* translators: %s: page */
  96. $title = sprintf( __( 'Orders (page %d)', 'woocommerce' ), intval( $wp->query_vars['orders'] ) );
  97. } else {
  98. $title = __( 'Orders', 'woocommerce' );
  99. }
  100. break;
  101. case 'view-order':
  102. $order = wc_get_order( $wp->query_vars['view-order'] );
  103. /* translators: %s: order number */
  104. $title = ( $order ) ? sprintf( __( 'Order #%s', 'woocommerce' ), $order->get_order_number() ) : '';
  105. break;
  106. case 'downloads':
  107. $title = __( 'Downloads', 'woocommerce' );
  108. break;
  109. case 'edit-account':
  110. $title = __( 'Account details', 'woocommerce' );
  111. break;
  112. case 'edit-address':
  113. $title = __( 'Addresses', 'woocommerce' );
  114. break;
  115. case 'payment-methods':
  116. $title = __( 'Payment methods', 'woocommerce' );
  117. break;
  118. case 'add-payment-method':
  119. $title = __( 'Add payment method', 'woocommerce' );
  120. break;
  121. case 'lost-password':
  122. $title = __( 'Lost password', 'woocommerce' );
  123. break;
  124. default:
  125. $title = '';
  126. break;
  127. }
  128. return apply_filters( 'woocommerce_endpoint_' . $endpoint . '_title', $title, $endpoint );
  129. }
  130. /**
  131. * Endpoint mask describing the places the endpoint should be added.
  132. *
  133. * @since 2.6.2
  134. * @return int
  135. */
  136. public function get_endpoints_mask() {
  137. if ( 'page' === get_option( 'show_on_front' ) ) {
  138. $page_on_front = get_option( 'page_on_front' );
  139. $myaccount_page_id = get_option( 'woocommerce_myaccount_page_id' );
  140. $checkout_page_id = get_option( 'woocommerce_checkout_page_id' );
  141. if ( in_array( $page_on_front, array( $myaccount_page_id, $checkout_page_id ), true ) ) {
  142. return EP_ROOT | EP_PAGES;
  143. }
  144. }
  145. return EP_PAGES;
  146. }
  147. /**
  148. * Add endpoints for query vars.
  149. */
  150. public function add_endpoints() {
  151. $mask = $this->get_endpoints_mask();
  152. foreach ( $this->get_query_vars() as $key => $var ) {
  153. if ( ! empty( $var ) ) {
  154. add_rewrite_endpoint( $var, $mask );
  155. }
  156. }
  157. }
  158. /**
  159. * Add query vars.
  160. *
  161. * @param array $vars Query vars.
  162. * @return array
  163. */
  164. public function add_query_vars( $vars ) {
  165. foreach ( $this->get_query_vars() as $key => $var ) {
  166. $vars[] = $key;
  167. }
  168. return $vars;
  169. }
  170. /**
  171. * Get query vars.
  172. *
  173. * @return array
  174. */
  175. public function get_query_vars() {
  176. return apply_filters( 'woocommerce_get_query_vars', $this->query_vars );
  177. }
  178. /**
  179. * Get query current active query var.
  180. *
  181. * @return string
  182. */
  183. public function get_current_endpoint() {
  184. global $wp;
  185. foreach ( $this->get_query_vars() as $key => $value ) {
  186. if ( isset( $wp->query_vars[ $key ] ) ) {
  187. return $key;
  188. }
  189. }
  190. return '';
  191. }
  192. /**
  193. * Parse the request and look for query vars - endpoints may not be supported.
  194. */
  195. public function parse_request() {
  196. global $wp;
  197. // Map query vars to their keys, or get them if endpoints are not supported.
  198. foreach ( $this->get_query_vars() as $key => $var ) {
  199. if ( isset( $_GET[ $var ] ) ) { // WPCS: input var ok, CSRF ok.
  200. $wp->query_vars[ $key ] = sanitize_text_field( wp_unslash( $_GET[ $var ] ) ); // WPCS: input var ok, CSRF ok.
  201. } elseif ( isset( $wp->query_vars[ $var ] ) ) {
  202. $wp->query_vars[ $key ] = $wp->query_vars[ $var ];
  203. }
  204. }
  205. }
  206. /**
  207. * Are we currently on the front page?
  208. *
  209. * @param WP_Query $q Query instance.
  210. * @return bool
  211. */
  212. private function is_showing_page_on_front( $q ) {
  213. return $q->is_home() && 'page' === get_option( 'show_on_front' );
  214. }
  215. /**
  216. * Is the front page a page we define?
  217. *
  218. * @param int $page_id Page ID.
  219. * @return bool
  220. */
  221. private function page_on_front_is( $page_id ) {
  222. return absint( get_option( 'page_on_front' ) ) === absint( $page_id );
  223. }
  224. /**
  225. * Hook into pre_get_posts to do the main product query.
  226. *
  227. * @param WP_Query $q Query instance.
  228. */
  229. public function pre_get_posts( $q ) {
  230. // We only want to affect the main query.
  231. if ( ! $q->is_main_query() ) {
  232. return;
  233. }
  234. // Fix for endpoints on the homepage.
  235. if ( $this->is_showing_page_on_front( $q ) && ! $this->page_on_front_is( $q->get( 'page_id' ) ) ) {
  236. $_query = wp_parse_args( $q->query );
  237. if ( ! empty( $_query ) && array_intersect( array_keys( $_query ), array_keys( $this->get_query_vars() ) ) ) {
  238. $q->is_page = true;
  239. $q->is_home = false;
  240. $q->is_singular = true;
  241. $q->set( 'page_id', (int) get_option( 'page_on_front' ) );
  242. add_filter( 'redirect_canonical', '__return_false' );
  243. }
  244. }
  245. // When orderby is set, WordPress shows posts on the front-page. Get around that here.
  246. if ( $this->is_showing_page_on_front( $q ) && $this->page_on_front_is( wc_get_page_id( 'shop' ) ) ) {
  247. $_query = wp_parse_args( $q->query );
  248. if ( empty( $_query ) || ! array_diff( array_keys( $_query ), array( 'preview', 'page', 'paged', 'cpage', 'orderby' ) ) ) {
  249. $q->set( 'page_id', (int) get_option( 'page_on_front' ) );
  250. $q->is_page = true;
  251. $q->is_home = false;
  252. // WP supporting themes show post type archive.
  253. if ( current_theme_supports( 'woocommerce' ) ) {
  254. $q->set( 'post_type', 'product' );
  255. } else {
  256. $q->is_singular = true;
  257. }
  258. }
  259. }
  260. // Fix product feeds.
  261. if ( $q->is_feed() && $q->is_post_type_archive( 'product' ) ) {
  262. $q->is_comment_feed = false;
  263. }
  264. // Special check for shops with the PRODUCT POST TYPE ARCHIVE on front.
  265. if ( current_theme_supports( 'woocommerce' ) && $q->is_page() && 'page' === get_option( 'show_on_front' ) && absint( $q->get( 'page_id' ) ) === wc_get_page_id( 'shop' ) ) {
  266. // This is a front-page shop.
  267. $q->set( 'post_type', 'product' );
  268. $q->set( 'page_id', '' );
  269. if ( isset( $q->query['paged'] ) ) {
  270. $q->set( 'paged', $q->query['paged'] );
  271. }
  272. // Define a variable so we know this is the front page shop later on.
  273. wc_maybe_define_constant( 'SHOP_IS_ON_FRONT', true );
  274. // Get the actual WP page to avoid errors and let us use is_front_page().
  275. // This is hacky but works. Awaiting https://core.trac.wordpress.org/ticket/21096.
  276. global $wp_post_types;
  277. $shop_page = get_post( wc_get_page_id( 'shop' ) );
  278. $wp_post_types['product']->ID = $shop_page->ID;
  279. $wp_post_types['product']->post_title = $shop_page->post_title;
  280. $wp_post_types['product']->post_name = $shop_page->post_name;
  281. $wp_post_types['product']->post_type = $shop_page->post_type;
  282. $wp_post_types['product']->ancestors = get_ancestors( $shop_page->ID, $shop_page->post_type );
  283. // Fix conditional Functions like is_front_page.
  284. $q->is_singular = false;
  285. $q->is_post_type_archive = true;
  286. $q->is_archive = true;
  287. $q->is_page = true;
  288. // Remove post type archive name from front page title tag.
  289. add_filter( 'post_type_archive_title', '__return_empty_string', 5 );
  290. // Fix WP SEO.
  291. if ( class_exists( 'WPSEO_Meta' ) ) {
  292. add_filter( 'wpseo_metadesc', array( $this, 'wpseo_metadesc' ) );
  293. add_filter( 'wpseo_metakey', array( $this, 'wpseo_metakey' ) );
  294. }
  295. } elseif ( ! $q->is_post_type_archive( 'product' ) && ! $q->is_tax( get_object_taxonomies( 'product' ) ) ) {
  296. // Only apply to product categories, the product post archive, the shop page, product tags, and product attribute taxonomies.
  297. return;
  298. }
  299. $this->product_query( $q );
  300. }
  301. /**
  302. * Pre_get_posts above may adjust the main query to add WooCommerce logic. When this query is done, we need to ensure
  303. * all custom filters are removed.
  304. *
  305. * This is done here during the_posts filter. The input is not changed.
  306. *
  307. * @param array $posts Posts from WP Query.
  308. * @return array
  309. */
  310. public function remove_product_query_filters( $posts ) {
  311. $this->remove_ordering_args();
  312. return $posts;
  313. }
  314. /**
  315. * WP SEO meta description.
  316. *
  317. * Hooked into wpseo_ hook already, so no need for function_exist.
  318. *
  319. * @return string
  320. */
  321. public function wpseo_metadesc() {
  322. return WPSEO_Meta::get_value( 'metadesc', wc_get_page_id( 'shop' ) );
  323. }
  324. /**
  325. * WP SEO meta key.
  326. *
  327. * Hooked into wpseo_ hook already, so no need for function_exist.
  328. *
  329. * @return string
  330. */
  331. public function wpseo_metakey() {
  332. return WPSEO_Meta::get_value( 'metakey', wc_get_page_id( 'shop' ) );
  333. }
  334. /**
  335. * Query the products, applying sorting/ordering etc.
  336. * This applies to the main WordPress loop.
  337. *
  338. * @param WP_Query $q Query instance.
  339. */
  340. public function product_query( $q ) {
  341. if ( ! is_feed() ) {
  342. $ordering = $this->get_catalog_ordering_args();
  343. $q->set( 'orderby', $ordering['orderby'] );
  344. $q->set( 'order', $ordering['order'] );
  345. if ( isset( $ordering['meta_key'] ) ) {
  346. $q->set( 'meta_key', $ordering['meta_key'] );
  347. }
  348. }
  349. // Query vars that affect posts shown.
  350. $q->set( 'meta_query', $this->get_meta_query( $q->get( 'meta_query' ), true ) );
  351. $q->set( 'tax_query', $this->get_tax_query( $q->get( 'tax_query' ), true ) );
  352. $q->set( 'wc_query', 'product_query' );
  353. $q->set( 'post__in', array_unique( (array) apply_filters( 'loop_shop_post_in', array() ) ) );
  354. // Work out how many products to query.
  355. $q->set( 'posts_per_page', $q->get( 'posts_per_page' ) ? $q->get( 'posts_per_page' ) : apply_filters( 'loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page() ) );
  356. // Store reference to this query.
  357. self::$product_query = $q;
  358. do_action( 'woocommerce_product_query', $q, $this );
  359. }
  360. /**
  361. * Remove the query.
  362. */
  363. public function remove_product_query() {
  364. remove_action( 'pre_get_posts', array( $this, 'pre_get_posts' ) );
  365. }
  366. /**
  367. * Remove ordering queries.
  368. */
  369. public function remove_ordering_args() {
  370. remove_filter( 'posts_clauses', array( $this, 'order_by_price_asc_post_clauses' ) );
  371. remove_filter( 'posts_clauses', array( $this, 'order_by_price_desc_post_clauses' ) );
  372. remove_filter( 'posts_clauses', array( $this, 'order_by_popularity_post_clauses' ) );
  373. remove_filter( 'posts_clauses', array( $this, 'order_by_rating_post_clauses' ) );
  374. }
  375. /**
  376. * Returns an array of arguments for ordering products based on the selected values.
  377. *
  378. * @param string $orderby Order by param.
  379. * @param string $order Order param.
  380. * @return array
  381. */
  382. public function get_catalog_ordering_args( $orderby = '', $order = '' ) {
  383. // Get ordering from query string unless defined.
  384. if ( ! $orderby ) {
  385. $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( (string) wp_unslash( $_GET['orderby'] ) ) : wc_clean( get_query_var( 'orderby' ) ); // WPCS: sanitization ok, input var ok, CSRF ok.
  386. if ( ! $orderby_value ) {
  387. if ( is_search() ) {
  388. $orderby_value = 'relevance';
  389. } else {
  390. $orderby_value = apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby', 'menu_order' ) );
  391. }
  392. }
  393. // Get order + orderby args from string.
  394. $orderby_value = explode( '-', $orderby_value );
  395. $orderby = esc_attr( $orderby_value[0] );
  396. $order = ! empty( $orderby_value[1] ) ? $orderby_value[1] : $order;
  397. }
  398. $orderby = strtolower( $orderby );
  399. $order = strtoupper( $order );
  400. $args = array(
  401. 'orderby' => $orderby,
  402. 'order' => ( 'DESC' === $order ) ? 'DESC' : 'ASC',
  403. 'meta_key' => '', // @codingStandardsIgnoreLine
  404. );
  405. switch ( $orderby ) {
  406. case 'menu_order':
  407. $args['orderby'] = 'menu_order title';
  408. break;
  409. case 'title':
  410. $args['orderby'] = 'title';
  411. $args['order'] = ( 'DESC' === $order ) ? 'DESC' : 'ASC';
  412. break;
  413. case 'relevance':
  414. $args['orderby'] = 'relevance';
  415. $args['order'] = 'DESC';
  416. break;
  417. case 'rand':
  418. $args['orderby'] = 'rand'; // @codingStandardsIgnoreLine
  419. break;
  420. case 'date':
  421. $args['orderby'] = 'date ID';
  422. $args['order'] = ( 'ASC' === $order ) ? 'ASC' : 'DESC';
  423. break;
  424. case 'price':
  425. if ( 'DESC' === $order ) {
  426. add_filter( 'posts_clauses', array( $this, 'order_by_price_desc_post_clauses' ) );
  427. } else {
  428. add_filter( 'posts_clauses', array( $this, 'order_by_price_asc_post_clauses' ) );
  429. }
  430. break;
  431. case 'popularity':
  432. $args['meta_key'] = 'total_sales'; // @codingStandardsIgnoreLine
  433. // Sorting handled later though a hook.
  434. add_filter( 'posts_clauses', array( $this, 'order_by_popularity_post_clauses' ) );
  435. break;
  436. case 'rating':
  437. $args['meta_key'] = '_wc_average_rating'; // @codingStandardsIgnoreLine
  438. $args['orderby'] = array(
  439. 'meta_value_num' => 'DESC',
  440. 'ID' => 'ASC',
  441. );
  442. break;
  443. }
  444. return apply_filters( 'woocommerce_get_catalog_ordering_args', $args );
  445. }
  446. /**
  447. * Handle numeric price sorting.
  448. *
  449. * @param array $args Query args.
  450. * @return array
  451. */
  452. public function order_by_price_asc_post_clauses( $args ) {
  453. global $wpdb, $wp_query;
  454. if ( isset( $wp_query->queried_object, $wp_query->queried_object->term_taxonomy_id, $wp_query->queried_object->taxonomy ) && is_a( $wp_query->queried_object, 'WP_Term' ) ) {
  455. $search_within_terms = get_terms( array(
  456. 'taxonomy' => $wp_query->queried_object->taxonomy,
  457. 'child_of' => $wp_query->queried_object->term_id,
  458. 'fields' => 'tt_ids',
  459. ) );
  460. $search_within_terms[] = $wp_query->queried_object->term_taxonomy_id;
  461. $args['join'] .= " INNER JOIN (
  462. SELECT post_id, min( meta_value+0 ) price
  463. FROM $wpdb->postmeta
  464. INNER JOIN (
  465. SELECT $wpdb->term_relationships.object_id
  466. FROM $wpdb->term_relationships
  467. WHERE 1=1
  468. AND $wpdb->term_relationships.term_taxonomy_id IN (" . implode( ',', array_map( 'absint', $search_within_terms ) ) . ")
  469. ) as products_within_terms ON $wpdb->postmeta.post_id = products_within_terms.object_id
  470. WHERE meta_key='_price' GROUP BY post_id ) as price_query ON $wpdb->posts.ID = price_query.post_id ";
  471. } else {
  472. $args['join'] .= " INNER JOIN ( SELECT post_id, min( meta_value+0 ) price FROM $wpdb->postmeta WHERE meta_key='_price' GROUP BY post_id ) as price_query ON $wpdb->posts.ID = price_query.post_id ";
  473. }
  474. $args['orderby'] = " price_query.price ASC, $wpdb->posts.ID ASC ";
  475. return $args;
  476. }
  477. /**
  478. * Handle numeric price sorting.
  479. *
  480. * @param array $args Query args.
  481. * @return array
  482. */
  483. public function order_by_price_desc_post_clauses( $args ) {
  484. global $wpdb, $wp_query;
  485. if ( isset( $wp_query->queried_object, $wp_query->queried_object->term_taxonomy_id, $wp_query->queried_object->taxonomy ) && is_a( $wp_query->queried_object, 'WP_Term' ) ) {
  486. $search_within_terms = get_terms( array(
  487. 'taxonomy' => $wp_query->queried_object->taxonomy,
  488. 'child_of' => $wp_query->queried_object->term_id,
  489. 'fields' => 'tt_ids',
  490. ) );
  491. $search_within_terms[] = $wp_query->queried_object->term_taxonomy_id;
  492. $args['join'] .= " INNER JOIN (
  493. SELECT post_id, max( meta_value+0 ) price
  494. FROM $wpdb->postmeta
  495. INNER JOIN (
  496. SELECT $wpdb->term_relationships.object_id
  497. FROM $wpdb->term_relationships
  498. WHERE 1=1
  499. AND $wpdb->term_relationships.term_taxonomy_id IN (" . implode( ',', array_map( 'absint', $search_within_terms ) ) . ")
  500. ) as products_within_terms ON $wpdb->postmeta.post_id = products_within_terms.object_id
  501. WHERE meta_key='_price' GROUP BY post_id ) as price_query ON $wpdb->posts.ID = price_query.post_id ";
  502. } else {
  503. $args['join'] .= " INNER JOIN ( SELECT post_id, max( meta_value+0 ) price FROM $wpdb->postmeta WHERE meta_key='_price' GROUP BY post_id ) as price_query ON $wpdb->posts.ID = price_query.post_id ";
  504. }
  505. $args['orderby'] = " price_query.price DESC, $wpdb->posts.ID DESC ";
  506. return $args;
  507. }
  508. /**
  509. * WP Core doens't let us change the sort direction for individual orderby params - https://core.trac.wordpress.org/ticket/17065.
  510. *
  511. * This lets us sort by meta value desc, and have a second orderby param.
  512. *
  513. * @param array $args Query args.
  514. * @return array
  515. */
  516. public function order_by_popularity_post_clauses( $args ) {
  517. global $wpdb;
  518. $args['orderby'] = "$wpdb->postmeta.meta_value+0 DESC, $wpdb->posts.post_date DESC";
  519. return $args;
  520. }
  521. /**
  522. * Appends meta queries to an array.
  523. *
  524. * @param array $meta_query Meta query.
  525. * @param bool $main_query If is main query.
  526. * @return array
  527. */
  528. public function get_meta_query( $meta_query = array(), $main_query = false ) {
  529. if ( ! is_array( $meta_query ) ) {
  530. $meta_query = array();
  531. }
  532. $meta_query['price_filter'] = $this->price_filter_meta_query();
  533. return array_filter( apply_filters( 'woocommerce_product_query_meta_query', $meta_query, $this ) );
  534. }
  535. /**
  536. * Appends tax queries to an array.
  537. *
  538. * @param array $tax_query Tax query.
  539. * @param bool $main_query If is main query.
  540. * @return array
  541. */
  542. public function get_tax_query( $tax_query = array(), $main_query = false ) {
  543. if ( ! is_array( $tax_query ) ) {
  544. $tax_query = array(
  545. 'relation' => 'AND',
  546. );
  547. }
  548. // Layered nav filters on terms.
  549. if ( $main_query ) {
  550. foreach ( $this->get_layered_nav_chosen_attributes() as $taxonomy => $data ) {
  551. $tax_query[] = array(
  552. 'taxonomy' => $taxonomy,
  553. 'field' => 'slug',
  554. 'terms' => $data['terms'],
  555. 'operator' => 'and' === $data['query_type'] ? 'AND' : 'IN',
  556. 'include_children' => false,
  557. );
  558. }
  559. }
  560. $product_visibility_terms = wc_get_product_visibility_term_ids();
  561. $product_visibility_not_in = array( is_search() && $main_query ? $product_visibility_terms['exclude-from-search'] : $product_visibility_terms['exclude-from-catalog'] );
  562. // Hide out of stock products.
  563. if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) ) {
  564. $product_visibility_not_in[] = $product_visibility_terms['outofstock'];
  565. }
  566. // Filter by rating.
  567. if ( isset( $_GET['rating_filter'] ) ) { // WPCS: input var ok, CSRF ok.
  568. $rating_filter = array_filter( array_map( 'absint', explode( ',', $_GET['rating_filter'] ) ) ); // WPCS: input var ok, CSRF ok, Sanitization ok.
  569. $rating_terms = array();
  570. for ( $i = 1; $i <= 5; $i ++ ) {
  571. if ( in_array( $i, $rating_filter, true ) && isset( $product_visibility_terms[ 'rated-' . $i ] ) ) {
  572. $rating_terms[] = $product_visibility_terms[ 'rated-' . $i ];
  573. }
  574. }
  575. if ( ! empty( $rating_terms ) ) {
  576. $tax_query[] = array(
  577. 'taxonomy' => 'product_visibility',
  578. 'field' => 'term_taxonomy_id',
  579. 'terms' => $rating_terms,
  580. 'operator' => 'IN',
  581. 'rating_filter' => true,
  582. );
  583. }
  584. }
  585. if ( ! empty( $product_visibility_not_in ) ) {
  586. $tax_query[] = array(
  587. 'taxonomy' => 'product_visibility',
  588. 'field' => 'term_taxonomy_id',
  589. 'terms' => $product_visibility_not_in,
  590. 'operator' => 'NOT IN',
  591. );
  592. }
  593. return array_filter( apply_filters( 'woocommerce_product_query_tax_query', $tax_query, $this ) );
  594. }
  595. /**
  596. * Return a meta query for filtering by price.
  597. *
  598. * @return array
  599. */
  600. private function price_filter_meta_query() {
  601. if ( isset( $_GET['max_price'] ) || isset( $_GET['min_price'] ) ) { // WPCS: input var ok, CSRF ok.
  602. $meta_query = wc_get_min_max_price_meta_query( $_GET ); // WPCS: input var ok, CSRF ok.
  603. $meta_query['price_filter'] = true;
  604. return $meta_query;
  605. }
  606. return array();
  607. }
  608. /**
  609. * Get the main query which product queries ran against.
  610. *
  611. * @return array
  612. */
  613. public static function get_main_query() {
  614. return self::$product_query;
  615. }
  616. /**
  617. * Get the tax query which was used by the main query.
  618. *
  619. * @return array
  620. */
  621. public static function get_main_tax_query() {
  622. $tax_query = isset( self::$product_query->tax_query, self::$product_query->tax_query->queries ) ? self::$product_query->tax_query->queries : array();
  623. return $tax_query;
  624. }
  625. /**
  626. * Get the meta query which was used by the main query.
  627. *
  628. * @return array
  629. */
  630. public static function get_main_meta_query() {
  631. $args = self::$product_query->query_vars;
  632. $meta_query = isset( $args['meta_query'] ) ? $args['meta_query'] : array();
  633. return $meta_query;
  634. }
  635. /**
  636. * Based on WP_Query::parse_search
  637. */
  638. public static function get_main_search_query_sql() {
  639. global $wpdb;
  640. $args = self::$product_query->query_vars;
  641. $search_terms = isset( $args['search_terms'] ) ? $args['search_terms'] : array();
  642. $sql = array();
  643. foreach ( $search_terms as $term ) {
  644. // Terms prefixed with '-' should be excluded.
  645. $include = '-' !== substr( $term, 0, 1 );
  646. if ( $include ) {
  647. $like_op = 'LIKE';
  648. $andor_op = 'OR';
  649. } else {
  650. $like_op = 'NOT LIKE';
  651. $andor_op = 'AND';
  652. $term = substr( $term, 1 );
  653. }
  654. $like = '%' . $wpdb->esc_like( $term ) . '%';
  655. $sql[] = $wpdb->prepare( "(($wpdb->posts.post_title $like_op %s) $andor_op ($wpdb->posts.post_excerpt $like_op %s) $andor_op ($wpdb->posts.post_content $like_op %s))", $like, $like, $like ); // unprepared SQL ok.
  656. }
  657. if ( ! empty( $sql ) && ! is_user_logged_in() ) {
  658. $sql[] = "($wpdb->posts.post_password = '')";
  659. }
  660. return implode( ' AND ', $sql );
  661. }
  662. /**
  663. * Get an array of attributes and terms selected with the layered nav widget.
  664. *
  665. * @return array
  666. */
  667. public static function get_layered_nav_chosen_attributes() {
  668. if ( ! is_array( self::$_chosen_attributes ) ) {
  669. self::$_chosen_attributes = array();
  670. $attribute_taxonomies = wc_get_attribute_taxonomies();
  671. if ( ! empty( $attribute_taxonomies ) ) {
  672. foreach ( $attribute_taxonomies as $tax ) {
  673. $attribute = wc_sanitize_taxonomy_name( $tax->attribute_name );
  674. $taxonomy = wc_attribute_taxonomy_name( $attribute );
  675. $filter_terms = ! empty( $_GET[ 'filter_' . $attribute ] ) ? explode( ',', wc_clean( wp_unslash( $_GET[ 'filter_' . $attribute ] ) ) ) : array(); // WPCS: sanitization ok, input var ok, CSRF ok.
  676. if ( empty( $filter_terms ) || ! taxonomy_exists( $taxonomy ) ) {
  677. continue;
  678. }
  679. $query_type = ! empty( $_GET[ 'query_type_' . $attribute ] ) && in_array( $_GET[ 'query_type_' . $attribute ], array( 'and', 'or' ), true ) ? wc_clean( wp_unslash( $_GET[ 'query_type_' . $attribute ] ) ) : ''; // WPCS: sanitization ok, input var ok, CSRF ok.
  680. self::$_chosen_attributes[ $taxonomy ]['terms'] = array_map( 'sanitize_title', $filter_terms ); // Ensures correct encoding.
  681. self::$_chosen_attributes[ $taxonomy ]['query_type'] = $query_type ? $query_type : apply_filters( 'woocommerce_layered_nav_default_query_type', 'and' );
  682. }
  683. }
  684. }
  685. return self::$_chosen_attributes;
  686. }
  687. /**
  688. * Remove the add-to-cart param from pagination urls.
  689. *
  690. * @param string $url URL.
  691. * @return string
  692. */
  693. public function remove_add_to_cart_pagination( $url ) {
  694. return remove_query_arg( 'add-to-cart', $url );
  695. }
  696. // @codingStandardsIgnoreStart
  697. /**
  698. * Order by rating post clauses.
  699. *
  700. * @deprecated 3.0.0
  701. * @param array $args
  702. * @return array
  703. */
  704. public function order_by_rating_post_clauses( $args ) {
  705. global $wpdb;
  706. wc_deprecated_function( 'order_by_rating_post_clauses', '3.0' );
  707. $args['fields'] .= ", AVG( $wpdb->commentmeta.meta_value ) as average_rating ";
  708. $args['where'] .= " AND ( $wpdb->commentmeta.meta_key = 'rating' OR $wpdb->commentmeta.meta_key IS null ) ";
  709. $args['join'] .= "
  710. LEFT OUTER JOIN $wpdb->comments ON($wpdb->posts.ID = $wpdb->comments.comment_post_ID)
  711. LEFT JOIN $wpdb->commentmeta ON($wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id)
  712. ";
  713. $args['orderby'] = "average_rating DESC, $wpdb->posts.post_date DESC";
  714. $args['groupby'] = "$wpdb->posts.ID";
  715. return $args;
  716. }
  717. /**
  718. * Return a meta query for filtering by rating.
  719. *
  720. * @deprecated 3.0.0 Replaced with taxonomy.
  721. * @return array
  722. */
  723. public function rating_filter_meta_query() {
  724. return array();
  725. }
  726. /**
  727. * Returns a meta query to handle product visibility.
  728. *
  729. * @deprecated 3.0.0 Replaced with taxonomy.
  730. * @param string $compare (default: 'IN')
  731. * @return array
  732. */
  733. public function visibility_meta_query( $compare = 'IN' ) {
  734. return array();
  735. }
  736. /**
  737. * Returns a meta query to handle product stock status.
  738. *
  739. * @deprecated 3.0.0 Replaced with taxonomy.
  740. * @param string $status (default: 'instock')
  741. * @return array
  742. */
  743. public function stock_status_meta_query( $status = 'instock' ) {
  744. return array();
  745. }
  746. /**
  747. * Layered nav init.
  748. *
  749. * @deprecated 2.6.0
  750. */
  751. public function layered_nav_init() {
  752. wc_deprecated_function( 'layered_nav_init', '2.6' );
  753. }
  754. /**
  755. * Get an unpaginated list all product IDs (both filtered and unfiltered). Makes use of transients.
  756. *
  757. * @deprecated 2.6.0 due to performance concerns
  758. */
  759. public function get_products_in_view() {
  760. wc_deprecated_function( 'get_products_in_view', '2.6' );
  761. }
  762. /**
  763. * Layered Nav post filter.
  764. *
  765. * @deprecated 2.6.0 due to performance concerns
  766. *
  767. * @param mixed $deprecated Deprecated.
  768. */
  769. public function layered_nav_query( $deprecated ) {
  770. wc_deprecated_function( 'layered_nav_query', '2.6' );
  771. }
  772. /**
  773. * Search post excerpt.
  774. *
  775. * @deprecated 3.2.0 - Not needed anymore since WordPress 4.5.
  776. */
  777. public function search_post_excerpt( $where = '' ) {
  778. wc_deprecated_function( 'WC_Query::search_post_excerpt', '3.2.0', 'Excerpt added to search query by default since WordPress 4.5.' );
  779. return $where;
  780. }
  781. /**
  782. * Remove the posts_where filter.
  783. * @deprecated 3.2.0 - Nothing to remove anymore because search_post_excerpt() is deprecated.
  784. */
  785. public function remove_posts_where() {
  786. wc_deprecated_function( 'WC_Query::remove_posts_where', '3.2.0', 'Nothing to remove anymore because search_post_excerpt() is deprecated.' );
  787. }
  788. // @codingStandardsIgnoreEnd
  789. }