在 wp-admin 列中显示每个 woocommerce 变体库存数量

Display each woocommerce variations stock quantity in wp-admin column

我所有的 woocommerce 产品都是可变产品。他们每个人都有相同的变化 'male' 和 'female'。

我正在尝试在 wp-admin 的产品概览中为它们中的每一个添加一列,两者都显示该变体的库存数量。

我包含了以下显示 'male' 和 'female' 之和的代码。有没有办法只查询其中一个?

function add_qty_admin( $column ) {
    if (!isset($columns['total_qty']))
    $columns['total_qty'] = "Totaal in voorraad";
    return $columns;
}
add_filter( 'manage_posts_columns', 'add_qty_admin' );

function admin_post_data_row($column_name, $post_id)
{
global $wpdb;
switch($column_name)
{
    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 p.id = s.post_id
                  AND s.meta_key = '_stock'";

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

    default:
        break;
}
}
add_action( 'manage_posts_custom_column', 'admin_post_data_row', 10, 2);

假设您的产品属性是 "Gender" (所以分类是 "pa_gender") 并且有 2 个术语 "Male" 和 "Female",以下代码将在管理产品列表中添加一个自定义列,其中包含带有 "Male" 项的变体的总数量和带有 "Female".

的变体的总数量
// Add a custom column to admin product list
add_filter( 'manage_edit-product_columns', 'product_variations_total_quantity_column', 10, 1 );
function product_variations_total_quantity_column( $columns ) {
    $columns['gender_qty'] = __("Stock totals", "woocommerce");

    return $columns;
}

// Display the data for this cutom column on admin product list
add_action( 'manage_product_posts_custom_column', 'product_variations_total_quantity_values', 10, 2 );
function product_variations_total_quantity_values( $column, $post_id ) {
    if( $column === 'gender_qty' ) {
        // Define the product attribute taxonomy (always start with "pa_")
        $taxonomy = 'pa_gender';

        echo '<table><tr>
            <td>M: '   . get_gender_qty( $post_id, 'male', $taxonomy )   . '</td>
            <td>F: ' . get_gender_qty( $post_id, 'female', $taxonomy ) . '</td>
        </tr></table>';
    }
}

// Get the total quantity of variations with a specific product attribute term slug
function get_gender_qty( $post_id, $term_slug, $taxonomy ) {
    global $wpdb;

    return (int) $wpdb->get_var($wpdb->prepare("
        SELECT sum(pm.meta_value)
        FROM {$wpdb->prefix}posts p
        INNER JOIN {$wpdb->prefix}postmeta pm ON p.id = pm.post_id
        INNER JOIN {$wpdb->prefix}postmeta pm2 ON p.id = pm2.post_id
        WHERE p.post_type = 'product_variation'
        AND p.post_status = 'publish'
        AND p.post_parent = %d
        AND pm.meta_key = '_stock'
        AND pm2.meta_key = '%s'
        AND pm2.meta_value = '%s'
    ", $post_id, 'attribute_'.$taxonomy, $term_slug ) );
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。