Home / Archive / MemberPress: Generate Invoice Numbers for Zero Amount Transactions
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Generate Invoice Numbers for Zero Amount Transactions

This code snippet ensures invoice numbers are generated for transactions with zero amounts in MemberPress.

By default, MemberPress PDF Invoices doesn't automatically create invoice numbers for free transactions, which can cause gaps in your invoice sequence and accounting records.

Code Preview
php
<?php
/**
 * MemberPress - Generate Invoice Numbers for Zero Amount Transactions
 * 
 * Creates invoice numbers for transactions with zero amounts to maintain
 * accounting consistency.
 */
function mepr_create_invoice_number( $event ) {
    // Fetch MemberPress options
    $mepr_options = MeprOptions::fetch();
    // Get the transaction data from the event
    $transaction = $event->get_data();
    
    // Check if the transaction amount is negative
    if( $transaction->amount < 0 ) {
        return; // Exit the function if the amount is negative
    }
    // Check if the transaction already has an invoice number
    if( MePdfInvoiceNumber::find_invoice_num_by_txn_id( $transaction->id ) ) {
        return; // Exit the function if an invoice number already exists
    }
    // Get the next available invoice number
    $invoice_no = absint( MePdfInvoiceNumber::next_invoice_num() );
    
    // Check if the invoice number is valid
    if( $invoice_no <= 0 ) {
        return; // Exit the function if the invoice number is invalid
    }
    // Create a new invoice number object and assign the values
    $invoice_number = new MePdfInvoiceNumber();
    $invoice_number->invoice_number = absint( $invoice_no );
    $invoice_number->transaction_id = absint( $transaction->id );
    
    // Store the invoice number
    $invoice_number->store();
}
// Add the action to trigger the function when a transaction is completed
add_action( 'mepr-event-transaction-completed', 'mepr_create_invoice_number' );

Comments

Add a Comment