Skip to content

Instantly share code, notes, and snippets.

@anisur2805
Last active December 25, 2023 05:57
Show Gist options
  • Save anisur2805/294667d750d508c384313568a1d227ef to your computer and use it in GitHub Desktop.
Save anisur2805/294667d750d508c384313568a1d227ef to your computer and use it in GitHub Desktop.
Complex query with SQL
<?php
function get_order_meta_by_key3( $meta_key = 'order_status' ) {
// Check if the data is already cached.
$cache_key = 'order_meta_cache_' . $meta_key;
$cached_data = get_transient( $cache_key );
if ( false !== $cached_data ) {
return $cached_data;
}
global $wpdb;
$posts_table = $wpdb->prefix . 'posts';
$postmeta_table = $wpdb->prefix . 'postmeta';
$hub_paged = 1;
$posts_per_page = 10;
$query = "
SELECT COUNT(mt1.meta_value) AS total, mt1.meta_value
FROM $posts_table
INNER JOIN $postmeta_table ON ($posts_table.ID = $postmeta_table.post_id)
INNER JOIN $postmeta_table AS mt1 ON ($posts_table.ID = mt1.post_id)
INNER JOIN $postmeta_table AS mt2 ON ($posts_table.ID = mt2.post_id)
WHERE
$postmeta_table.meta_key = 'custom_color_match' AND $postmeta_table.meta_value = '0'
AND mt1.meta_key = 'order_status'
AND mt1.meta_value NOT IN ('Delivered', 'Invoice Sent', 'Waiting', 'Blockchain Pending', 'Pending')
AND (
(mt2.meta_key = 'product_cat' AND mt2.meta_value LIKE '%wood-hoods-product-category%')
OR (mt2.meta_key = 'product_cat' AND mt2.meta_value LIKE '%hall-trees%')
OR (mt2.meta_key = 'product_cat' AND mt2.meta_value LIKE '%island-wood-hoods%')
OR (mt2.meta_key = 'origin' AND mt2.meta_value = 'Hub')
)
AND ( $posts_table.post_type = 'all_order' )
GROUP BY mt1.meta_value
ORDER BY total DESC;
";
$offset = ( $hub_paged - 1 ) * $posts_per_page;
$results = $wpdb->get_results( $wpdb->prepare( $query, $posts_per_page, $offset ), ARRAY_A ); // phpcs:ignore
$count = array();
foreach ( $results as $result ) {
$order_status = trim( preg_replace( '/\s+/', ' ', $result['meta_value'] ) );
if ( empty( $order_status ) ) {
continue;
}
$count[ $order_status ] = $result['total'];
}
// Cache the data for future use.
set_transient( $cache_key, $count, 12 * HOUR_IN_SECONDS );
return $count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment