Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save UraraReika/4c0b11f33873f63c40bf68bb10589e2d to your computer and use it in GitHub Desktop.
Save UraraReika/4c0b11f33873f63c40bf68bb10589e2d 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 IDs.
*/
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() ) {
/**
* It's better to do it separately to avoid performing unnecessary functions, even if they are not significant.
* If you know what you're using this code for, you don't need to use this check.
*/
if ( ! function_exists( 'WC' ) ) {
return;
}
$user_id = get_current_user_id();
if ( ! $user_id ) {
return;
}
$orders = wc_get_orders( array(
'customer_id' => $user_id,
'limit' => -1,
'status' => array_keys( wc_get_is_paid_statuses() ), // Using a more universal way to obtain order statuses. Get list of statuses which are consider 'paid'.
) );
// It is mandatory to check for orders; if there are no orders, further actions are pointless.
if ( ! $orders ) {
return;
}
$products_ids = array();
foreach ( $orders as $order ) {
$items = $order->get_items();
foreach ( $items as $item ) {
$products_ids[] = $item->get_product_id(); // There is a special method for obtaining the product identifier in an order.
}
}
// Remove duplicates in the array. Since the same products are possible in different orders.
$product_ids = array_unique( $product_ids );
return implode( ',', $product_ids );
}
}
new Purchased_Products_Macro();
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment