Woocommerce Shortcode – Return multiple $values of single $key in front end

Ok so here is my problem: I have a custom field attached to each product where there are a number of checkboxes… The customer checks a maximum of 4 boxes. The results are held in metadata under $key ‘Selection’.

I can return only the last of these four choices… How do I list all the selections in a table next to the customer name… Please see below.

This is a shortcode that accepts the product ID so it can be shown anywhere!

Much appreciated!

<?php
// Add Shortcode
function pcl_shortcode( $atts ) {
$output = '';

// Attributes
$customer_atts = shortcode_atts( array(
    'product' => get_the_id(),
), $atts );

// Code
global $post, $wpdb;
$post_id = $customer_atts['product'];
$pcl_orders = '';
$columns = array();
$customerquery = "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta woim 
    LEFT JOIN {$wpdb->prefix}woocommerce_order_items oi 
    ON woim.order_item_id = oi.order_item_id 
    WHERE meta_key = '_product_id' AND meta_value = %d
    GROUP BY order_id;";
$order_ids = $wpdb->get_col( $wpdb->prepare( $customerquery, $post_id ) );
$order_status = get_option( 'pcl_order_status_select', array('wc-completed') );
if( $order_ids ) {
    $args = array(
        'post_type'       =>'shop_order',
        'post__in'   => $order_ids,
        'posts_per_page' =>  999,
        'order'          => 'ASC',             
        'post_status' => $order_status,
    );
    $pcl_orders = new WP_Query( $args );
}
if($pcl_orders) {
    $output .= '<table>';
    foreach($pcl_orders->posts as $pcl_order) {
        $order = new WC_Order($pcl_order->ID);
        $output .= '<tr>';
        $output .= '<td>' . $order->billing_first_name . ' ' . $order->billing_last_name . '</td>';
        foreach($order->get_items() as $item) 

        // get an array of multiple values
        $output .= '<td>' . $item['Selection'] . '</td>';
        $output .= '</tr>';
    }
    $output .= '</table>';
}
return $output;
}

add_shortcode( 'woo_customer_list', 'pcl_shortcode' );

Read more here: Woocommerce Shortcode – Return multiple $values of single $key in front end

Leave a Reply

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