Skip to content
Advertisement

Creating a List of Available WooCommerce Coupon Codes and Display anywhere Using Shortcode

I am trying to generate a list of available coupons and to display them using a shortcode. I was hoping to generate the list using SQL and not “-1” since that’s heavier on the db from what I understand.

The error I get is this: Notice: Array to string conversion

add_shortcode('ac', 'coupon_list' );
function coupon_list() {

    // array for coupons, was hoping for a sql query instead but don't know how
    $args = array(
    'posts_per_page'   => -1,
    'orderby'          => 'title',
    'order'            => 'asc',
    'post_type'        => 'shop_coupon',
    'post_status'      => 'publish',
);

    $coupons = get_posts( $args );
        $coupon_names = array();
            foreach ( $coupons as $coupon ) {
        $coupon_name = $coupon->post_title;
        array_push( $coupon_names, $coupon_name );
    }

    // display all available coupons on product page
    echo $coupon_names;
}

Advertisement

Answer

There are 2 mistakes in your code: You are trying to display an array with echo and when using a shortcode function the data to display requires to be returned (not echoed).

The following function (shortcode), will display a coma separated string of all available coupon codes using a light SQL Query:

add_shortcode('ac', 'available_coupon_codes' );
function available_coupon_codes() {
    global $wpdb;

    // Get an array of all existing coupon codes
    $coupon_codes = $wpdb->get_col("SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon' AND post_status = 'publish' ORDER BY post_name ASC");

    // Display available coupon codes
    return implode(', ', $coupon_codes) ; // always use return in a shortcode
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


USAGE:

1) In the WordPress text editor of a post, a custom post or a page:

[ac]

2) On a php file or template:

echo available_coupon_codes();

or

echo do_shortcode('[ac]');

With a WP_Query (like in your code):

add_shortcode('ac', 'coupon_list' );
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

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

    // Display available coupon codes
    return implode(', ', $coupon_codes) ; // always use return in a shortcode
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Same usage than the first function

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement