| 1 |
<?php namespace TierPricingTable\Addons\GlobalTieredPricing\CPT; |
| 2 |
|
| 3 |
use TierPricingTable\Addons\GlobalTieredPricing\GlobalPricingRule; |
| 4 |
use WP_Query; |
| 5 |
|
| 6 |
/** |
| 7 |
* The rules list shows the rules in the order the storefront checks them (lowest priority number first, |
| 8 |
* newest first among equal numbers) unless a column sort is chosen. |
| 9 |
*/ |
| 10 |
class ListOrder { |
| 11 |
|
| 12 |
const ORDERBY = 'tpt_order'; |
| 13 |
|
| 14 |
public function __construct() { |
| 15 |
add_filter( 'posts_clauses', array( $this, 'orderClauses' ), 10, 2 ); |
| 16 |
} |
| 17 |
|
| 18 |
public function orderClauses( array $clauses, WP_Query $query ): array { |
| 19 |
if ( ! is_admin() || ! $query->is_main_query() || GlobalTieredPricingCPT::SLUG !== $query->get( 'post_type' ) ) { |
| 20 |
return $clauses; |
| 21 |
} |
| 22 |
|
| 23 |
$orderby = (string) $query->get( 'orderby' ); |
| 24 |
|
| 25 |
if ( '' !== $orderby && self::ORDERBY !== $orderby ) { |
| 26 |
return $clauses; // another column sorts the list |
| 27 |
} |
| 28 |
|
| 29 |
global $wpdb; |
| 30 |
|
| 31 |
// no column chosen: the resolution order (WordPress defaults "order" to DESC, which must not flip it) |
| 32 |
$direction = self::ORDERBY === $orderby && 'DESC' === strtoupper( (string) $query->get( 'order' ) ) ? 'DESC' : 'ASC'; |
| 33 |
$dateOrder = 'ASC' === $direction ? 'DESC' : 'ASC'; |
| 34 |
|
| 35 |
// rules saved before priorities existed have no meta row and sit at the default |
| 36 |
$clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} AS tpt_priority ON tpt_priority.post_id = {$wpdb->posts}.ID AND tpt_priority.meta_key = '_tpt_priority' "; |
| 37 |
$clauses['orderby'] = sprintf( 'COALESCE( tpt_priority.meta_value + 0, %d ) %s, %s.post_date %s', GlobalPricingRule::DEFAULT_PRIORITY, $direction, $wpdb->posts, $dateOrder ); |
| 38 |
|
| 39 |
return $clauses; |
| 40 |
} |
| 41 |
} |
| 42 |
|