在 WooCommerce 中自动将产品分配给定义的产品类别

Automatically assign products to a defined product category in WooCommerce

在 Woocommerce 中,如果产品具有特定的自定义字段值(使用高级自定义字段插件生成此字段),我会尝试自动将给定的产品类别分配给产品。

在我的 functions.php 我有 :

function auto_add_category ($product_id = 0) {

    if (!$product_id) return;
    $post_type = get_post_type($post_id);
    if ( "product" != $post_type ) return;

    $field = get_field("city");
    if($field == "Cassis"){
        $terms = get_the_terms( $post->ID, 'product_cat' );
        foreach ($terms as $term) {
            $product_cat_id = $term->term_id;
            if($product_cat_id != 93){
                wp_set_post_terms( $product_id, 93, 'product_cat', true );
            }
            break;
        }
    }
}
add_action('save_post','auto_add_category');

但这行不通。有什么想法吗?

您好像在使用 ACF?

get_field() 需要将 post id 传递给它,如果没有在循环中使用的话,所以你应该把那行写成 $field = get_field("city",$product_id);.

此外,将 $post->ID 替换为 $product_id get_the_terms()

希望对您有所帮助

对于 save_post 钩子有 3 个参数:

  • $post_id (post ID),
  • $post WP_Post 对象),
  • $update(无论是否更新现有 post:truefalse)。

ACF get_field() 函数工作 无需 任何需要在此处指定 post ID

此外,为了使您的代码更紧凑、轻便和高效,您应该使用条件函数 has_term() with term_exists() 而不是 get_the_terms() (+ foreach 循环) 即获取您网站上的所有现有产品类别……

所以你应该这样试试:

// Only on WooCommerce Product edit pages (Admin)
add_action( 'save_post', 'auto_add_product_category', 50, 3 );
function auto_add_product_category( $post_id, $post, $update ) {

    if ( $post->post_type != 'product') return; // Only products

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user's permissions.
    if ( ! current_user_can( 'edit_product', $post_id ) )
        return $post_id;

    if ( ! ( $post_id && function_exists( 'get_field' ) ) ) 
        return; // Exit if ACF is not enabled (just to be sure)

    if ( 'Cassis' != get_field( 'city' ) )
        return; // Exit if ACF field "city" has 'Cassis' as value

    $term_id = 93; // <== Your targeted product category term ID
    $taxonomy = 'product_cat'; // The taxonomy for Product category

    // If the product has not "93" category id and if "93" category exist
    if ( ! has_term( $term_id, 'product_cat', $post_id ) && term_exists( $term_id, $taxonomy ) )
        wp_set_post_terms( $post_id, $term_id, $taxonomy, true ); // we set this product category
}

代码进入活动子主题(或活动主题)的 function.php 文件。

经过测试并且有效。它应该也适合你。