Last active
March 18, 2024 16:41
-
-
Save Crocoblock/bcf96e00d54d84f38865d175d01fbe67 to your computer and use it in GitHub Desktop.
JetEngine Get purchased Woocommerce products macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} ); |
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
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
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 );