Francesco Di Candia Francesco Di Candia - 1 year ago 52
PHP Question

Woocommerce - Trying to get variable product quantity sum in admin

as in title, i'm trying to get sum of my variable product (for each product) in admin instead of 'out-of-stock' or 'in-stock' indication. I've variable product so i need sum of one variation to get all my product (ive a pant in different size and different colour but i need only sum of all size). Anyone got this before me?
Thanks in advance, Francesco

Answer Source

Finally i found solution. First of all added this

function add_qty_admin( $column ) {
        if (!isset($columns['total_qty']))
        $columns['total_qty'] = "Quantità";
        return $columns;
add_filter( 'manage_posts_columns', 'add_qty_admin' );

to functions.php in order to have a column in my backend.

Then i've added also this

function admin_post_data_row($column_name, $post_id)
    global $wpdb;
        case 'total_qty':
            $query = "SELECT sum(meta_value)
                      FROM $wpdb->posts AS p, $wpdb->postmeta AS s
                      WHERE p.post_parent = %d
                      AND p.post_type = 'product_variation'
                      AND p.post_status = 'publish'
                      AND = s.post_id
                      AND s.meta_key = '_stock'";

            $product_qty = $wpdb->get_var($wpdb->prepare($query,$post_id));
            if ($product_qty) echo $product_qty;

add_action( 'manage_posts_custom_column', 'admin_post_data_row', 10, 2);

where $query is SQL query that sum all _stock value in postmeta table for post_parent posts that are the variations of post_id.

Sorry for my poor english (i'm italian), i hope this code can be helpful fot other people. Francesco.