在wp-admin列中显示每个woocommerce的库存量

时间:2019-06-03 13:59:08

标签: php wordpress woocommerce stock wp-admin

我的所有woocommerce产品都是可变产品。他们每个人都有相同的变体“男”和“女”。

我正在尝试在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);

1 个答案:

答案 0 :(得分:1)

假设您的产品属性为“性别” (因此分类法为“ pa_gender”),并且有2个术语“男性”和“女性”,则以下代码将在admin中添加一个自定义列带有“ 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文件中。经过测试,可以正常工作。