Upendra Sharma Upendra Sharma - 3 months ago 13
PHP Question

Enabling permanently review checkbox option for all WooCommerce products

I would like to enable review checkbox permanently for all existing products and for newly added products too. I have looked in WooCommerce settings, but thatís not possible. I have search over internet, and I didnít find anything.

How can I bulk edit all existing products to get reviews Enabled?

When we add a new product it should be automatically checked too.

Is there a way to do it?

Is it possible?

Thanks in advance.

Answer

This is possible, but you will need 2 functions. One to update all existing products inn your shop, that you will use only one time, and the other for all newly published products.

Step 1 - Use this just once on function.php and go to front-end and navigate to any page. Once done comment this code or remove it. All your existing products have been updated.

// Updating all products that have a 'comment_status' => 'closed' to 'open'

function updating_existing_products_once(){
    $args = array(
        // WC product post type
        'post_type'   => 'product',
        // all posts
        'numberposts' => -1,
        'comment_status' => 'closed',
        'post_status' => 'publish',
    );

    $shop_products = get_posts( $args );
    foreach( $shop_products as $item){
        $product = new WC_Product($item->ID);
        wp_update_post( array(
            'ID'    => $item->ID,
            'comment_status' => 'open',
        ) );
    }
}
// After usage comment this line below
updating_existing_products_once();

Step 2 - This function will update new created products that have a 'comment_status' => 'closed' to 'open' (reviews on WooCommerce)

add_action('transition_post_status', 'creating_a_new_product', 10, 3);
function creating_a_new_product($new_status, $old_status, $post) {
    if( $old_status != 'publish' && $new_status == 'publish' && !empty($post->ID)  && in_array( $post->post_type, array( 'product') ) ) {
        if ($post->comment_status != 'open' ){
            $product = new WC_Product($post->ID);
            wp_update_post( array(
                'ID'    => $post->ID,
                'comment_status' => 'open',
            ) );
        }
    }
}

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.