phpwordpresswoocommercehook-woocommercereview

How to add new column with content to WooCommerce product reviews table?


I want to show a new column in WooCommerce product reviews. I tried to use below code to display new column But this code does not work. How can I do this?

add_filter( 'woocommerce_product_reviews_table_columns', 'my_custom_reviews_column', 9999 );
function my_custom_reviews_column( $my_column ){
    $new_column = array(
        'custom' => 'Custom',
    );
    $my_column = array_slice( $my_column, 0, 3, true ) + $new_column + array_slice( $my_column, 3, NULL, true );
   return $my_column;
}
 
add_action( 'woocommerce_product_reviews_table_column_', 'my_custom_column_content', 10, 2 );
function my_custom_column_content( $column, $product_id ){
    if ( $column == 'custom' ) {
      echo 'test';
    }
}

I think the problem is the 'woocommerce_product_reviews_table_column_'.

The code I wrote only displays the new column title.


Solution

  • woocommerce_product_reviews_table_column_ is invalid hook, you need to join $column_name as well in this hook at the end.

    From the example, your column name is custom so the hook name will be woocommerce_product_reviews_table_column_custom and you don't need to if ( $column == 'custom' ) inside the function.

    You'll get $item param in action to use, which is the review/reply object. and if you have to get product ID using that object than you'll have to use $item->comment_post_ID to do that.

    Here is your final code:

    add_action( 'woocommerce_product_reviews_table_column_custom', 'my_custom_column_content' );
    function my_custom_column_content( $item ){
        $product_id = $item->comment_post_ID;
        
        echo 'Product ID:' . $product_id;
    }