Skip to content

Instantly share code, notes, and snippets.

@FrankEBailey
Created November 2, 2023 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FrankEBailey/c4ea801133700c73f8f0f0d96313145b to your computer and use it in GitHub Desktop.
Save FrankEBailey/c4ea801133700c73f8f0f0d96313145b to your computer and use it in GitHub Desktop.
add_action( 'elementor/query/meditations', function( $query ) {
global $wpdb;
// Only proceed if it's the correct widget and the user is logged in.
if ( ! is_user_logged_in() ) {
return;
}
$current_user = wp_get_current_user();
// Define the category slug for the products you want to retrieve.
$category_slug = 'meditations';
// Custom SQL to retrieve product IDs.
$sql = "
SELECT DISTINCT items.product_id
FROM {$wpdb->prefix}woocommerce_order_items AS items
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON items.order_item_id = itemmeta.order_item_id
INNER JOIN {$wpdb->prefix}posts AS posts ON items.order_id = posts.ID
INNER JOIN {$wpdb->prefix}term_relationships AS tr ON items.product_id = tr.object_id
INNER JOIN {$wpdb->prefix}term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN {$wpdb->prefix}terms AS t ON tt.term_id = t.term_id
WHERE posts.post_status = 'wc-completed'
AND itemmeta.meta_key = '_customer_user'
AND itemmeta.meta_value = %s
AND tt.taxonomy = 'product_cat'
AND t.slug = %s
";
// Prepare and execute the SQL query.
$prepared_sql = $wpdb->prepare($sql, $current_user->ID, $category_slug);
$product_ids = $wpdb->get_col($prepared_sql);
// If no products are found, return to prevent errors.
if ( empty( $product_ids ) ) {
$query->set( 'post__in', [0] );
return;
}
// Modify the main query to only include the specific product IDs.
$query->set( 'post__in', $product_ids );
$query->set( 'orderby', 'post__in' );
$query->set( 'posts_per_page', -1 ); // You can change this to any number you prefer
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment