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

时间:2018-01-17 15:20:04

标签: php wordpress woocommerce categories product

在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');

但这不起作用。好吗?

2 个答案:

答案 0 :(得分:1)

对于save_post钩子,有3个参数:

  • $post_id (帖子ID)
  • $post WP_Post对象)
  • $update(这是否是现有的帖子正在更新:truefalse)。

ACF get_field()功能没有需要在此处指定帖子ID

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

所以你应该这样尝试:

// 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文件。

经过测试和工作。它也适合你。

答案 1 :(得分:0)

好像你正在使用ACF?

如果未在循环中使用,

get_field()要求将帖子ID传递给它,因此您应该将该行$field = get_field("city",$product_id);设为。

另外,将$post->ID替换为$product_id

中的get_the_terms()

希望有所帮助