map = $map; } /** * This handler is responsible for the 'orderby' key. * It supports any key that is present in its configuration map. */ public function supports( string $key, string $entity_type ): bool { // This handler is only for 'orderby', and it checks if the specific // orderby value (e.g., 'title', 'conditions') is in its map. // The check happens inside apply() for more flexibility. return $key === 'orderby'; } /** * Applies the 'orderby' and 'order' arguments to the WP_Query args. * * @param array $query_args The current array of WP_Query arguments. * @param mixed $value The 'orderby' value from the REST request (e.g., 'title'). * @param string $entity_type The entity type being queried. * * @return array The modified array of WP_Query arguments. */ public function apply( array $query_args, mixed $value, string $entity_type ): array { $orderby_key = sanitize_key( (string) $value ); $mapped_config = $this->map[ $orderby_key ] ?? null; if ( ! $mapped_config ) { $query_args['orderby'] = 'date'; return $query_args; } // Case 1: Sort by a meta field if ( is_array( $mapped_config ) && isset( $mapped_config['meta_key'] ) ) { // A plain meta_key sort inner-joins and drops entities without the key; EXISTS OR NOT EXISTS keeps them. // Order by the NOT EXISTS clause: its LEFT JOIN is keyed, so missing values are NULL, not another meta row. $sort_clause = [ 'key' => $mapped_config['meta_key'], 'compare' => 'NOT EXISTS', ]; if ( ( $mapped_config['orderby'] ?? 'meta_value' ) === 'meta_value_num' ) { $sort_clause['type'] = 'NUMERIC'; } if ( ! isset( $query_args['meta_query'] ) || ! is_array( $query_args['meta_query'] ) ) { $query_args['meta_query'] = []; } if ( ! isset( $query_args['meta_query']['relation'] ) ) { $query_args['meta_query']['relation'] = 'AND'; } $query_args['meta_query'][] = [ 'relation' => 'OR', [ 'key' => $mapped_config['meta_key'], 'compare' => 'EXISTS', ], self::META_SORT_CLAUSE => $sort_clause, ]; $query_args['orderby'] = self::META_SORT_CLAUSE; } else { // Case 2: Simple sort by title, date, etc. $query_args['orderby'] = $mapped_config; } return $query_args; } }