<?php
/**
 * Add an affiliate's tracked affiliate coupons to the exported affiliates .csv file.
 * For Easy Digital Downloads & WooCommerce integrations.
 *
 * @link https://andrew.dev/snippets/add-an-affiliates-tracked-affiliate-coupons-to-the-affiliates-csv-file/
 */

/**
 * Add a "Coupons" column to exported Affiliates .csv file.
 */
function am_affwp_add_coupons_csv_column( $cols ) {
	// Add the "Coupons" column to the .csv file.
	$cols['coupons'] = 'Coupons';

	return $cols;

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

/**
 * Add the affiliates's tracked affiliate coupons to the new "Coupons" column in the .csv file.
 * The coupons will be comma separated.
 */
function am_affwp_get_coupon_csv_data( $affiliates ) {

	global $wpdb;

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

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

		$post_ids = $wpdb->get_results(
			"
			SELECT post_id
			FROM $wpdb->postmeta
			WHERE ( meta_key = 'affwp_discount_affiliate' OR meta_key = 'affwp_coupon_affiliate' )
			AND meta_value = $affiliate_id
			"
		);

		// Get all the coupon post IDs from post meta.
		$coupon_ids = wp_list_pluck( $post_ids, 'post_id' );

		// Create an array to hold the coupons.
		$coupons = array();

		if ( $coupon_ids ) {

			// Loop through the coupon ids.
			foreach ( $coupon_ids as $coupon_id ) {

				// Get the post type of each coupon post ID.
				switch ( get_post_type( $coupon_id ) ) {

					// WooCommerce.
					case 'shop_coupon':
						if ( 'publish' == get_post_status( $coupon_id ) ) {
							$coupons[] = get_the_title( $coupon_id );
						}

					// Easy Digital Downloads.
					case 'edd_discount':
						if ( 'active' == get_post_status( $coupon_id ) ) {
							$coupons[] = get_the_title( $coupon_id );
						}

					break;

				}

			}
		}

		// Add the coupons to the "Coupons" column in the CSV file and separate
		// with commas if there's more than one.
		$affiliates[$key]['coupons'] = implode( ', ', $coupons );

	}

	return $affiliates;

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

Leave a Reply

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