Skip to content

Instantly share code, notes, and snippets.

@claudiulodro
Last active April 19, 2017 21:47
Show Gist options
  • Save claudiulodro/923316882ebf73d7e9c00b29df429879 to your computer and use it in GitHub Desktop.
Save claudiulodro/923316882ebf73d7e9c00b29df429879 to your computer and use it in GitHub Desktop.
WC_Query data store query processing demo implementation
<?php
class WC_Data_Store_WP {
// . . .
/**
* Map WC_Query args into a format that WP_Query can parse.
* @param $args - array of query args from a WC_Query.
* @return array of query args that WP_Query can parse.
* @todo not a big fan of this method's name.
*/
protected function get_automapped_wp_query_args( $args ) {
// Start with empty default WP_Query args.
$query_args = new WP_Query()->fill_query_vars( array() );
foreach( $args as $key => $value ) {
if ( '' === $value || array() === $value ) {
continue;
}
// Handle standard WP_Query args.
if ( isset( $query_args[ $key ] ) && 'meta_query' !== $key ) {
$query_args[ $key ] = $value;
continue;
}
// Generate meta queries for internal keys stored in metadata.
// This will automatically handle 'width', 'downloadable', 'usage_limit', etc.
if ( isset( $this->internal_meta_keys[ '_' . $key ] ) ) {
if ( ! isset( $query_args['meta_query'] ) ) {
$query_args['meta_query'] = array();
}
$query_args['meta_query'][] = array(
'key' => '_' . $key,
'value' => $value,
'compare' => 'LIKE', // Use '=' instead?
);
}
}
// Handle custom user-specified meta queries.
if ( isset( $args['meta_query'] ) ) {
if ( ! isset( $query_args['meta_query'] ) ) {
$query_args['meta_query'] = $args['meta_query'];
} else {
$query_args['meta_query'][] = $args['meta_query'];
}
}
return $query_args;
}
// . . .
}
class WC_Product_Data_Store_CPT {
// . . .
public function get_products( $args ) {
$wp_query_args = $this->get_automapped_wp_query_args( $args );
// Process special-case args that can't automatically be parsed by get_automapped_wp_query_args
if ( ! empty( $args['category'] ) ) {
unset( $wp_query_args['category'] );
$wp_query_args['tax_query'][] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $args['category'],
);
}
if ( ! empty( $args['shipping_class'] ) ) {
$wp_query_args['tax_query'][] = array(
'taxonomy' => 'product_shipping_class',
'field' => 'slug',
'terms' => $args['shipping_class'],
);
}
// There's some more query processing that has to happen here: search, other tax_query-based mappings, etc.
$products = new WP_Query( $wp_query_args );
$return = array_map( 'wc_get_product', $products->posts );
}
// . . .
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment