Home / Archive / MemberPress: Display Purchase Information With Shortcode
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Display Purchase Information With Shortcode

The code snippet registers a new shortcode: [purchase_info]. Adding this shortcode will display the latest MemberPress purchase information for the currently logged-in user, including the purchase value, transaction ID, and user’s email.
The sample code will display the latest MemberPress purchase value in US dollars ($). In addition, the code will show the “No purchase information found.” message if the user has no purchases.

To adjust the currency, the code snippet should to be manually adjusted by replacing the currency symbol or formatting on these lines:

Purchase Value: $" . number_format($value, 2) . "

To modify the message displayed in case the user has no purchases, replace the “No purchase information found.” Text with the new test on this line:

return "No purchase information found.";

Code Preview
php
<?php
function custom_purchase_info_shortcode() {
    global $wpdb;
    // Get the current user ID
    $user_id = get_current_user_id();
    // Get the latest MemberPress transaction for this user
    $latest_transaction = $wpdb->get_row( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}mepr_transactions 
        WHERE user_id = %d 
        ORDER BY id DESC 
        LIMIT 1",
        $user_id
    ) );
    if ($latest_transaction) {
        $value = $latest_transaction->amount;
        $transaction_id = $latest_transaction->trans_num;
        $user_email = get_userdata($user_id)->user_email;
        // Format the output
        $output = "
            <p><strong>Purchase Value:</strong> $" . number_format($value, 2) . "</p>
            <p><strong>Transaction ID:</strong> " . $transaction_id . "</p>
            <p><strong>Your Email:</strong> " . $user_email . "</p>
        ";
        return $output;
    } else {
        return "No purchase information found.";
    }
}
add_shortcode('purchase_info', 'custom_purchase_info_shortcode');

Comments

Add a Comment