[英]Add a custom "Sale Price" column to admin products list in Woocommerce
[英]Add new column to WooCommerce admin products list with discount percentage on sale products
我正在嘗試在后端的附加列中顯示正在銷售的簡單產品的百分比折扣。
我使用了下面的代碼
add_filter( 'manage_edit-product_columns', 'discount_column', 20 );
function discount_column( $col_th ) {
return wp_parse_args( array( 'discount' => 'Discount' ), $col_th );
}
add_action( 'manage_posts_custom_column', 'discount_col' );
function discount_col( $column_id ) {
if( $column_id == 'discount' )
$saleprice = get_post_meta( get_the_ID(), '_sale_price', true );
$regularprice = get_post_meta( get_the_ID(), '_regular_price', true );
if ($saleprice > 0) {
$discountperc = ($regularprice -$saleprice) /$regularprice * 100;
echo (round($discountperc,2)). '%';
}
}
但是我收到多個(相同的)錯誤:
Undefined variable: saleprice
有人可以指導我如何做到這一點嗎?
更新 06/21:現在也適用於可變產品。
不必通過get_post_meta
獲取 postmeta 數據,因為您可以通過$postid
訪問產品 object。
一旦擁有產品object,您就可以訪問各種產品信息。
所以你得到:
// Column header
function filter_manage_edit_product_columns( $columns ) {
// Add column
$columns['discount'] = __( 'Discount', 'woocommerce' );
return $columns;
}
add_filter( 'manage_edit-product_columns', 'filter_manage_edit_product_columns', 10, 1 );
// Column content
function action_manage_product_posts_custom_column( $column, $postid ) {
// Compare
if ( $column == 'discount' ) {
// Get product object
$product = wc_get_product( $postid );
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Product is on sale
if ( $product->is_on_sale() ) {
// Output
echo '<ul>';
// Simple products
if ( $product->is_type( 'simple' ) ) {
// Get regular price
$regular_price = $product->get_regular_price();
// Get sale price
$sale_price = $product->get_sale_price();
// Calculate discount percentage
$discount_percentage = ( ( $sale_price - $regular_price ) / $regular_price ) * 100;
// Output
echo '<li>' . abs( number_format( $discount_percentage, 2, '.', '') ) . '%' . '</li>';
// Variable products
} elseif ( $product->is_type( 'variable' ) ) {
foreach( $product->get_visible_children() as $variation_id ) {
// Get product
$variation = wc_get_product( $variation_id );
// Get regular price
$regular_price = $variation->get_regular_price();
// Get sale price
$sale_price = $variation->get_sale_price();
// NOT empty
if ( ! empty ( $sale_price ) ) {
// Get name
$name = $variation->get_name();
// Calculate discount percentage
$discount_percentage = ( ( $sale_price - $regular_price ) / $regular_price ) * 100;
// Output
echo '<li>' . $name . '</li>';
echo '<li>' . abs( number_format( $discount_percentage, 2, '.', '') ) . '%' . '</li>';
}
}
}
// Output
echo '</ul>';
}
}
}
}
add_action( 'manage_product_posts_custom_column', 'action_manage_product_posts_custom_column', 10, 2 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.