为所有 WooCommerce 产品启用永久审查复选框选项

Enabling permanently review checkbox option for all WooCommerce products

我想为所有现有产品和新添加的产品永久启用审核复选框。我查看了 WooCommerce 设置,但那是不可能的。我在互联网上搜索过,但我没有找到任何东西。

如何批量编辑所有现有产品以获得评论已启用

当我们添加新产品时,它也应该被自动检查。

有办法吗?
可能吗?

提前致谢。

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.

第 1 步 - 在 function.php 上只使用一次,然后转到前端并导航到任何页面。完成后评论此代码或将其删除。 您现有的所有产品都已更新。

// 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();

第 2 步 - 此函数将更新具有 'comment_status' => 'closed' 的新创建产品到 'open' (对 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',
            ) );
        }
    }
}

此代码位于您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

此代码已经过测试并且有效。

除了 LoicTheAztec 的出色回答外,我还想为 "Step 1" 添加一个不同的选项。

您可以 运行 一个不需要遍历循环的简单查询:

global $wpdb;
$wpdb->query("UPDATE {$wpdb->posts} SET comment_status = 'open' WHERE post_type = 'product'");

请注意 故意 遗漏了 WHERE 子句中的 comment_statuspost_status。未发布的产品具有开放评论状态并不重要,已经 comment_status 设置为开放的产品正在重新设置为开放也无关紧要。

将上面的代码添加到你的主题的functions.php文件的底部,然后运行一次后注释掉:

// Commented out so it won't run
// global $wpdb;
// $wpdb->query("UPDATE {$wpdb->posts} SET comment_status = 'open' WHERE post_type = 'product'");

我知道这是个老问题,但如果 LoicTheAztec 的回答不起作用(比如对我来说),下面的功能可能会对某人有所帮助。默认情况下,它会使用 "Add product" 页面上的 jQuery 检查评论的复选框。我希望能帮助别人,干杯! :-)

add_action( 'woocommerce_product_options_advanced', 'enable_reviews_by_default' );
function enable_reviews_by_default() {
?>
    <script>
        (function($){
            $('input[name=comment_status]').prop('checked', true);
        })(jQuery);
    </script>
<?php
}

顺便说一句,一种立即修复事物的肮脏方法(可逆)。所有功劳都归功于 Evgeniy

https://developer.wordpress.org/reference/functions/comments_open/

虽然原来的帖子讨论了如何到处禁用评论,但我把效果颠倒了:)

这使您无法根据每个产品做出决定,因为会覆盖整个站点的复选框!

免责声明:风险自负!

add_filter( 'comments_open', '__return_true' );