Search code examples
phpwordpresswoocommercecoupon

Get a list of available WooCommerce coupons in a select field


As part of a plugin I am creating with the WooCommerce API, I need to get the coupons to show in the select field. Here is the relevant piece of code:

// Get coupons
function coupon_list() {
    $coupon_posts = get_posts( array(
        'posts_per_page'   => -1,
        'orderby'          => 'name',
        'order'            => 'asc',
        'post_type'        => 'shop_coupon',
        'post_status'      => 'publish',
    ) );

    $coupon_codes = []; 

    foreach( $coupon_posts as $coupon_post) {
        $coupon_codes[] = $coupon_post->post_name;
    }

    return implode($coupon_codes) ;
}

$settings = array(
    'coupon_to_use' => array(
        'name'      => __( 'Coupon to use'),
        'type'      => 'select',
        'default'   => '',
        'desc'      => __( 'Use this.'),
        'desc_tip'  => true,
        'id'        => 'the_coupon_type',
        'options'   => array(
            coupon_list(), // This is where I am stuck
        )
    )
);

return apply_filters( 'the_coupon_settings', $settings );

The options array should have something like this...

'options'   => array(
    'coupon_1' => __( 'Coupon 1'),
    'coupon_2' => __( 'Coupon 2'),
)

..but coupon_list() is just returning a string of coupon names. How can I fix this?


Solution

  • Your function doesn't return an array, but a string by the use of implode() and you should use $coupon_post->post_name for the array keys:

    function coupon_list() {
        $coupon_posts = get_posts( array(
            'posts_per_page'   => -1,
            'orderby'          => 'name',
            'order'            => 'asc',
            'post_type'        => 'shop_coupon',
            'post_status'      => 'publish',
        ) );
    
        $coupon_codes = []; // Initializing
    
        // Push to array
        foreach ( $coupon_posts as $coupon_post ) {
            $coupon_codes[$coupon_post->post_name] = $coupon_post->post_title;
        }
    
        // Return coupon array
        return $coupon_codes;
    }
    

    In WooCommerce you can then use woocommerce_form_field() - ( type' => 'select' ) to create a drop-down list (frontend) - for the backend you can use woocommerce_wp_select().

    For example to display this on the WooCommerce single product page (frontend), you can use:

    function action_woocommerce_single_product_summary() {
        // Add select field
        woocommerce_form_field( 'the_coupon_type', array(
            'type'      => 'select',
            'label'     => __( 'Coupon to use', 'woocommerce' ),
            'required'  => false,
            'options'   => coupon_list(),
        ),'' );
    }
    add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 9 );