更新 Woocommerce 3 中的产品可见性

JSt*_*hen 2 php methods wordpress product woocommerce

我正在使用几个带有 woocommerce/wordpress 的插件来制作它,这样我的每个产品变体都会作为单独的产品显示在我的产品列表中,但每种颜色中只设置一种显示(所以如果我有一个产品有 3 种尺寸和 3 个颜色,有 9 个产品,但由于每种颜色只能看到一个,因此列表中只显示了 3 个产品。)。我编写了一个脚本,一旦当前可见的产品缺货,它就会将可见性设置转移到相同颜色的下一个产品。

我遇到的问题是,即使一切看起来都正确,产品没有显示在产品列表中,直到我进入管理端,编辑产品,将可见性设置更改为隐藏,然后返回显示(以便它让我点击保存按钮,但页面加载时实际上没有任何变化),然后点击保存并按预期显示。

所以我一定在被查询的数据库中遗漏了一些东西,但我不知道是什么,posts 和 post_meta 表在管理端点击保存之前和之后看起来都一样。唯一更改的_edit_lock字段是 post_meta 表中的字段。

这是我为传输可见性设置而编写的脚本的一部分,我最初遇到了这个问题,发现这是因为该产品仍然标记为缺货,所以我最后添加了该行并且它似乎可以正常工作,但是现在有些东西否则导致它:

    ...
    // $child_id is the product that the visibility settings are being transferred to, it should at this point be hidden
    // $visibility is the settings of the product that was visibile


    // swap visibility settings of the products
    $child_visibility = get_post_meta($child_id,"_visibility",true);
    update_post_meta($product->get_id(),"_visibility",$child_visibility);
    update_post_meta($child_id,"_visibility",$visibility);


    // copy color taxonomies over in case they were not entered 
    // this saved time so that the admin only had to enter taxonomy information on the visible products
    $terms = get_the_terms( $product->get_id(), 'product_color');
    $termArray = array();
    foreach($terms as $term) {
        $termArray[] = $term->name;
    }
    wp_set_object_terms( $child_id, $termArray, 'product_color', false );

    // i dont remember what this was for
    delete_transient( 'jck_wssv_term_counts' );

    // make sure new item is not marked out of stock
    wp_remove_object_terms( $child_id, 'outofstock', 'product_visibility' );
    wp_remove_object_terms( $child_id, 'exclude-from-catalog', 'product_visibility' );
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 5

从 Woocommerce 3 开始,产品可见性现在由'product_visibility'术语的自定义分类法处理,'exclude-from-catalog'并且'exclude-from-search'……请参阅此线程线程

因此,您应该以这种方式使用WC_ProductCRUD setter 方法set_catalog_visibility()

// Get an instance of the product variation from a defined ID
$child_product = wc_get_product(child_id);
// Change the product visibility
$child_product->set_catalog_visibility('visible');
// Save and sync the product visibility
$child_product->save();
Run Code Online (Sandbox Code Playgroud)

这也将更新瞬态缓存数据,并会做的伎俩......