Skip to content

Instantly share code, notes, and snippets.

@Crocoblock
Last active March 18, 2024 16:41
Show Gist options
  • Save Crocoblock/bcf96e00d54d84f38865d175d01fbe67 to your computer and use it in GitHub Desktop.
Save Crocoblock/bcf96e00d54d84f38865d175d01fbe67 to your computer and use it in GitHub Desktop.
JetEngine Get purchased Woocommerce products macro
<?php
add_action( 'jet-engine/register-macros', function() {
/**
* Return purchased products.
*/
class Purchased_Products_Macro extends \Jet_Engine_Base_Macros {
public function macros_tag() {
return 'purchased_products';
}
public function macros_name() {
return esc_html__( 'Purchased products', 'jet-engine' );
}
public function macros_args() {
return array();
}
public function macros_callback( $args = array() ) {
$user_id = get_current_user_id();
if ( ! $user_id || ! function_exists( 'WC' ) ) {
return;
}
$args = array(
'customer_id' => $user_id,
'limit' => -1,
'status' => array(
'completed',
),
);
$orders = wc_get_orders( $args );
$products = array();
foreach ( $orders as $order ) {
$items = $order->get_items();
foreach ( $items as $item ) {
$products[] = $item->get_data()['product_id'];
}
}
return implode( ',', $products );
}
}
new Purchased_Products_Macro();
} );
@0xbg
Copy link

0xbg commented Jun 2, 2023

This code has an issue as the return value can be empty, meaning that the JetEngine/Query Builder query will return all products, which is the opposite purpose of this code.

Two proposed fixes:

#1 best practice to catch the error
// Fetch user orders
try {
$orders = wc_get_orders( $args );
} catch (Exception $e) {
error_log('Failed to get orders: ' . $e->getMessage());
return;
}

#2 the variable $products could be empty
// Check if products array is empty
// If the variable $products is empty, the resulting string will also be empty. In this case, the list will display all products available.
if (empty($products)) {
return '-1';
}
return implode( ',', $products );

@citizen-01
Copy link

citizen-01 commented Nov 29, 2023

Hey! @0xbg
You can add a fallback for macro in Custom Query to display no prodcuts, if the value is empty - https://prnt.sc/KTQZ0KecdoJE

@ashiqhosenbd
Copy link

I tried a lot using this code but it's not working with the query builder.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment