Paweł Skaba
Paweł Skaba

Reputation: 681

Woocommerce - display number of featured product orders

I would like to display a kind of summary on a subpage, how much currently my shop is selling featured products. Each month i will have only one featured item (after 30days im adding new one, changing status of previous product from featured to normal).

My current code looks like below:

function woo_featured_product_sales_qty( $atts, $content = null ) {
    $args = shortcode_atts( array(
        'status' => 'completed',
        'meta_query' => array(
            array(
                'post_type' => 'product',  
                'meta_key' => '_featured',  
                'meta_value' => 'yes', 
                'order' => 'DESC'
            )
        ),
    ), $atts );

    $status_list = $args['status'];

    $statuses = array_map( 'trim', explode( ',', $status_list ) );

    $order_count = 0;

    foreach ( $statuses as $status ) {

        $status = str_replace( $status, 'wc-' . $status, $status );

        $total_orders = wp_count_posts( 'shop_order' )->$status;

        $order_count += $total_orders;
    }
    ob_start();

    echo $order_count;

    return ob_get_clean();
}

add_shortcode( 'featured_product_sales_qty', 'woo_featured_product_sales_qty' );

This code indeed shows total orders but as sum. What to do, to make it work properly? How to display that number of orders according to current featured products?

Upvotes: 1

Views: 445

Answers (1)

rnevius
rnevius

Reputation: 27092

I would simplify things, and do a simple WP_Query for these posts:

function woo_featured_product_sales_qty( $atts, $content = null ) {
    $args = shortcode_atts( array(
        'status' => 'completed',
        'meta_query' => array(
            array(
                'post_type' => 'product',  
                'meta_key' => '_featured',  
                'meta_value' => 'yes', 
                'order' => 'DESC'
            )
        ),
    ), $atts );

    $status_list = $args['status'];

    $statuses = array_map( 'trim', explode( ',', $status_list ) );

    $query_args = array(
        'post_status' => $statuses,
        'meta_query' => $args['meta_query'],
    );
    $posts = new WP_Query( $query_args );

    return $posts->have_posts() ? $posts->found_posts : 0;
}

add_shortcode( 'featured_product_sales_qty', 'woo_featured_product_sales_qty' );

Upvotes: 1

Related Questions