Track Who Created a WooCommerce Coupon

Code Snippets Coding Blog Custom Code Snippets PHP PHP Development Tech Tutorials Theme Optimization Tutorials Woocommerce WooCommerce Customization WooCommerce Development Woocommerce Hooks WooCommerce Tips Wordpress WordPress Development
✨

Track Who Created a WooCommerce Coupon Tutorial/Guide

WooCommerce does not log the user who created a coupon by default. To enable this, you can add a small snippet to store and display the creator info. Follow these steps: Step 1: Edit your theme’s functions.php file or build a custom plugin. Step 2: Add the following code:

// Track who created the coupon
function save_coupon_creator($post_id) {
    $coupon = get_post($post_id);
    $user_id = get_current_user_id();
    update_post_meta($post_id, 'coupon_creator', $user_id);
}
add_action('woocommerce_new_coupon', 'save_coupon_creator');

// Show creator info on the coupon edit page
function display_coupon_creator($coupon) {
    $creator_id = get_post_meta($coupon->get_id(), 'coupon_creator', true);
    if ($creator_id) {
        $creator_name = get_the_author_meta('display_name', $creator_id);
        echo 'Coupon Creator: ' . $creator_name . ''; 
    } 
} 
add_action('woocommerce_coupon_options_usage', 'display_coupon_creator');

Step 3: Save and apply the changes. This will track and display the coupon creator using custom meta. Want to show this in the coupon list table too? Here's how: Step 1: Add this to your functions.php:

// Add column for coupon creator
function add_coupon_creator_column($columns) {
    $columns['coupon_creator'] = __('Coupon Creator', 'your-text-domain');
    return $columns;
}
add_filter('manage_edit-shop_coupon_columns', 'add_coupon_creator_column');

// Show creator in table
function display_coupon_creator_column($column, $coupon_id) {
    if ($column === 'coupon_creator') {
        $creator_id = get_post_meta($coupon_id, 'coupon_creator', true);
        echo $creator_id ? get_the_author_meta('display_name', $creator_id) : '-';
    }
}
add_action('manage_shop_coupon_posts_custom_column', 'display_coupon_creator_column', 10, 2);

// Sortable column
function make_coupon_creator_column_sortable($columns) {
    $columns['coupon_creator'] = 'coupon_creator';
    return $columns;
}
add_filter('manage_edit-shop_coupon_sortable_columns', 'make_coupon_creator_column_sortable');

// Sorting logic
function modify_coupon_creator_column_sorting($query) {
    if (is_admin() && $query->is_main_query() && $query->get('orderby') === 'coupon_creator') {
        $query->set('meta_key', 'coupon_creator');
        $query->set('orderby', 'meta_value_num');
    }
}
add_action('pre_get_posts', 'modify_coupon_creator_column_sorting');

This lets you view and sort WooCommerce coupons by their creator in the admin table. A great way to improve internal tracking and responsibility!  

πŸ’‘ Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.