Inventory_Presser_Plugin::modify_query_orderby( array $pieces )

Filter callback. Modifies a query’s ORDER BY clause to appropriately sort some meta values as numbers instead of strings while adding fields to the ORDER BY clause to account for all of the JOINs to the postmeta.


Parameters Parameters

$pieces

(array) (Required) All of a queries syntax organized into an array.


Top ↑

Return Return

(array) The changed array of database query fragments


Top ↑

Source Source

File: inventory-presser.php

				return;
			}

			// Get original meta query.
			$meta_query = $query->get( 'meta_query' );
			if ( ! is_array( $meta_query ) ) {
				$meta_query = array();
			}

			$meta_query['relation'] = 'AND';
			$meta_query             = self::maybe_add_meta_query(
				$meta_query,
				apply_filters( 'invp_prefix_meta_key', 'price' ),
				(int) $_GET['max_price'],
				'<=',
				'numeric'
			);
			$query->set( 'meta_query', $meta_query );
		}

		/**
		 * Filter callback. Modifies a query's ORDER BY clause to appropriately
		 * sort some meta values as numbers instead of strings while adding fields
		 * to the ORDER BY clause to account for all of the JOINs to the postmeta.
		 *
		 * @param  array $pieces All of a queries syntax organized into an array.
		 * @return array The changed array of database query fragments
		 */
		public function modify_query_orderby( $pieces ) {
			/**
			 * Count the number of meta fields we have added to the query by parsing
			 * the join piece of the query
			 */
			global $wpdb;
			$meta_field_count = count( explode( "INNER JOIN $wpdb->postmeta AS", $pieces['join'] ) ) - 1;

			// Parse out the ASC or DESC sort direction from the end of the ORDER BY clause.
			$direction             = $this->get_last_word( $pieces['orderby'] );
			$acceptable_directions = array( 'ASC', 'DESC' );
			$direction             = ( in_array( $direction, $acceptable_directions, true ) ? ' ' . $direction : '' );

			/**
			 * Build a string to replace the existing ORDER BY field name
			 * Essentially, we are going to turn '{$wpdb->postmeta}.meta_value' into
			 * 'mt1.meta_value ASC, mt2.meta_value ASC, mt3.meta_value ASC'
			 * where the number of meta values is what we calculated in $meta_field_count
			 */