Forked from andrewlimaza/custom-pmpro-order-codes.php
Last active
September 6, 2021 10:28
-
-
Save ipokkel/c35656b60751d0fb3cdcb6f5df1a4806 to your computer and use it in GitHub Desktop.
Generate custom order codes / order numbers that increment for Paid Memberships Pro Orders [Date + Custom order sequence]
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 | |
/** | |
* Custom order codes for Paid Memberships Pro Orders. | |
* | |
* This code will take the date and order ID and create | |
* an order code from that such as "INV060920211", "INV060920212", "INV060920213" | |
* and increment with each order added. | |
* | |
* A fallback is in place that if "INV060920211" already exists for some order, | |
* it will just generate a random code to be safe. | |
* | |
* You can add this recipe to your site by creating a custom plugin | |
* or using the Code Snippets plugin available for free in the WordPress repository. | |
* Read this companion article for step-by-step directions on either method. | |
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
function pmpro_custom_order_codes( $code ) { | |
global $wpdb; | |
$last_id = $wpdb->get_var( "SELECT `id` FROM $wpdb->pmpro_membership_orders ORDER BY `id` DESC LIMIT 1" ); | |
$current_id = (int) $last_id + 1; | |
$prefix = apply_filters( 'pmpro_custom_order_prefix', 'INV' ); // You can change "INV" to something else or filter this from another plugin or custom code. | |
$today = date( 'dmY' ); // get date DDMMYYYY, e.g. 06092021 | |
// Merge prefix (INV) + date (06092021) + current_id (321), e.g. INV06092021321 | |
$code = $prefix . $today . $current_id; //Code cannot just be an integer and _must_contain_a_string_. | |
// We need to add a check to see if the order code is not taken, otherwise it will be an infinite loop. | |
$check = $wpdb->get_var( $wpdb->prepare( "SELECT `id` FROM $wpdb->pmpro_membership_orders WHERE code = %s LIMIT 1", $code ) ); | |
// If the code already exists or is only a number, just generate a random order code with 10 digits. | |
if ( $check || is_numeric( $code ) ) { | |
$code = wp_generate_password( 10, false, false ); | |
} | |
return $code; | |
} | |
add_filter( 'pmpro_random_code', 'pmpro_custom_order_codes', 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment