暫無描述

class-wc-query.php 32KB

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