<?php
/**
 * Add an affiliate’s WooCommerce store credit to the affiliates .csv file.
 *
 * @link https://andrew.dev/snippets/add-an-affiliates-woocommerce-store-credit-to-the-affiliates-csv-file/
 */

/**
 * Add a "Store Credit" column to exported Affiliates .csv file.
 */
function am_affwp_woocommerce_add_store_credit_column( $cols ) {

	$cols['store_credit'] = 'Store Credit';
	return $cols;

}
add_filter( 'affwp_export_csv_cols_affiliates', 'am_affwp_woocommerce_add_store_credit_column' );

/**
 * Add the affiliates's WooCommerce store credit to the new "Store Credit" column in the .csv file.
 */
function am_affwp_woocommerce_csv_data_store_credit( $affiliates ) {

	foreach ( $affiliates as $key => $affiliate ) {

		// Get the affiliate ID.
		$affiliate_id = $affiliate['affiliate_id'];

		// Get the affiliate's user ID, based on their affiliate ID.
		$user_id = affwp_get_affiliate_user_id( $affiliate_id );

		// Get the user's current store credit balance from user meta.
		$store_credit = get_user_meta( $user_id, 'affwp_wc_credit_balance', true );

		// Format the store credit amount.
		$store_credit = $store_credit ? affwp_format_amount( $store_credit ) : 0;

		// Add the store credit to the "Store Credit" column.
		$affiliates[$key]['store_credit'] = $store_credit;

	}

	return $affiliates;

}
add_filter( 'affwp_export_get_data_affiliates', 'am_affwp_woocommerce_csv_data_store_credit' );

Leave a Reply

Your email address will not be published. Required fields are marked *