Add a custom “Sale Price” column to admin products list in Woocommerce

那年仲夏 提交于 2021-02-10 15:56:08

问题


I am trying to add a Sale Price column to admin Products list in Woocommerce.

Here is my code:

   add_filter( 'manage_edit-product_columns', 'onsale_product_column', 10);

   function onsale_product_column($columns){
   $new_columns = [];
   foreach( $columns as $key => $column ){
      $new_columns[$key] = $columns[$key];
      if( $key == 'product_cat' ) {
           $new_columns['onsale'] = __( 'Sale Price','woocommerce');
       }
     }
    return $new_columns;
    }

    add_action( 'manage_product_posts_custom_column', 
    'onsale_product_column_content', 10, 2 );

    function onsale_product_column_content( $column, $product_id ){
    global $post;
    if( $column == 'onsale' ){
        if( $product_id->is_on_sale() ) {
            echo $product_id->get_sale_price();
        }
        echo '-';
    }
}

But it doesn't work. What I am doing wrong?


回答1:


There is some mistakes in your code… Try the following instead:

add_filter( 'manage_edit-product_columns', 'onsale_product_column', 10);
function onsale_product_column($columns){
    $new_columns = [];
    foreach( $columns as $key => $column ){
        $new_columns[$key] = $columns[$key];
        if( $key == 'product_cat' ) {
            $new_columns['onsale'] = __( 'Sale Price','woocommerce');
        }
    }
    return $new_columns;
}

add_action( 'manage_product_posts_custom_column', 'onsale_product_column_content', 10, 2 );
function onsale_product_column_content( $column, $post_id ){
    if( $column == 'onsale' ){
        global $post, $product;

        // Excluding variable and grouped products
        if( is_a( $product, 'WC_Product' ) && ! $product->is_type('grouped') &&
        ! $product->is_type('variable') && $product->is_on_sale() ) {
            echo strip_tags( wc_price( $product->get_sale_price() ) );
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and work.



来源:https://stackoverflow.com/questions/52896061/add-a-custom-sale-price-column-to-admin-products-list-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!