Php WooCommerce自动分配产品类别和产品状态

Php WooCommerce自动分配产品类别和产品状态,php,wordpress,woocommerce,hook-woocommerce,custom-taxonomy,Php,Wordpress,Woocommerce,Hook Woocommerce,Custom Taxonomy,我试图创建所有这些if语句: 如果勾选了产品类别A,则类别B将自动不勾选,产品状态变为“缺货” 如果未选中产品类别A,则类别B将自动选中 到目前为止,除了“缺货”部分,这两种说法都有效。你知道如何调用和设置股票状态吗 add_action( 'save_post', 'auto_add_product_category', 50, 3 ); function auto_add_product_category( $post_id, $post, $update ) { if ( $po

我试图创建所有这些if语句:

  • 如果勾选了产品类别A,则类别B将自动不勾选,产品状态变为“缺货”
  • 如果未选中产品类别A,则类别B将自动选中
  • 到目前为止,除了“缺货”部分,这两种说法都有效。你知道如何调用和设置股票状态吗

    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;
    
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            return $post_id;
    
        if ( ! current_user_can( 'edit_product', $post_id ) )
            return $post_id;
    
        $term_id_A = 116; //category A
        $term_id_B = 1459; //category B
        $terms = get_the_terms( $post_id, 'product_cat' );
        $term_ids = wp_list_pluck( $terms, 'term_id' );
    
        if(in_array($term_id_A, $term_ids) && ($key = array_search($term_id_B, $term_ids)) !== false) {
            unset($term_ids[$key]);
        } elseif(!in_array($term_id_A, $term_ids) && !in_array($term_id_B, $term_ids)) {
            $term_ids[] = $term_id_B;
        }
        wp_set_post_terms($post_id, $term_ids, 'product_cat');
    }
    

    您需要将代码的最后一位替换为:

    if(in_array($term_id_A, $term_ids) && ($key = array_search($term_id_B, $term_ids)) !== false) {
        //remove term A from the terms array:
        unset($term_ids[$key]);
        //set stock level to zero:
        $out_of_stock_staus = 'outofstock';
        // 1. Updating the stock quantity
        update_post_meta($post_id, '_stock', 0);
        // 2. Updating the stock quantity
        update_post_meta( $post_id, '_stock_status', wc_clean( $out_of_stock_staus ) );
        // 3. Updating post term relationship
        wp_set_post_terms( $post_id, 'outofstock', 'product_visibility', true );
        // And finally (optionally if needed)
        wc_delete_product_transients( $post_id ); // Clear/refresh the variation cache
    
    } elseif(!in_array($term_id_A, $term_ids) && !in_array($term_id_B, $term_ids)) {
        $term_ids[] = $term_id_B;
    }
    
    有关额外代码的进一步说明,请参见: