#php #wordpress #woocommerce #backend #product
#php #wordpress #woocommerce #серверная часть #продукт
Вопрос:
Я пытаюсь отобразить процентную скидку на простые товары, которые продаются, в дополнительном столбце в бэкэнде.
Я использовал приведенный ниже код
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
Может кто-нибудь рассказать мне, как это сделать?
Ответ №1:
ОБНОВЛЕНИЕ 06/21: теперь также работает для переменных продуктов.
Нет необходимости получать данные postmeta через get_post_meta
, потому что вы можете получить доступ к объекту product через $postid
.
Как только у вас есть объект product, у вас есть доступ ко всем видам информации о продукте.
Таким образом, вы получаете:
// 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 );