Skip to content

Instantly share code, notes, and snippets.

@s-a-s-k-i-a
Last active April 26, 2023 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-a-s-k-i-a/ad7f6b881ea195779ac471655e96de09 to your computer and use it in GitHub Desktop.
Save s-a-s-k-i-a/ad7f6b881ea195779ac471655e96de09 to your computer and use it in GitHub Desktop.
How to use an SQL query for multiple meta_key and meta_value pairs with PHP from WordPress Database - example: Finding FooEvents Cancelled Tickets
<?php
/**
*
* This function returns the number of canceled tickets of a specific FooEvents WooCommerce product.
* @author Saskia Teichmann | wp-studio.dev
*
* @param int $event_product_id.
* @return int
*/
function wpstudiodev_get_number_of_canceled_tickets($event_product_id){
global $wpdb;
$prefix = $wpdb->prefix;
$all_canceled_tickets_sql = "
SELECT *
FROM {$prefix}posts p
INNER JOIN {$prefix}postmeta pm1
ON ( p.ID = pm1.post_id )
INNER JOIN {$prefix}postmeta pm2
ON ( p.ID = pm2.post_id )
WHERE
p.post_type = 'event_magic_tickets'
AND p.post_status = 'publish'
AND ( pm1.meta_key = 'WooCommerceEventsProductID' AND pm1.meta_value = $event_product_id )
AND ( pm2.meta_key = 'WooCommerceEventsStatus' AND pm2.meta_value = 'Canceled' )
";
$all_canceled_tickets = $wpdb->get_results($all_canceled_tickets_sql);
$canceled_tickets_total = count( $all_canceled_tickets );
return $canceled_tickets_total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment