Woocommerce newProduct()分类法不起作用

时间:2014-07-15 23:54:23

标签: php attributes woocommerce product taxonomy

你能告诉我我做错了吗?

我向Woocommerce添加新产品的代码现在看起来像这样:

function newProduct( $idERP, $titulo, $conteudo, $preco, $precoDesconto, $sku, $peso, $comprimento, $largura, $altura, $estoque, $variacoes, $categorias ){

        global $woocommerce;

        $titulo = utf8_encode($titulo);
        $conteudo = utf8_encode($conteudo);

        $my_post = array(
          'post_title'    => $titulo,
          'post_content'  => $conteudo,
          'post_status'   => 'pending',
          'post_author'   => 6,
          'post_type'     =>'product'
        );
        $product_ID = wp_insert_post( $my_post );

        if ( $product_ID ){

          if( $preco == $precoDesconto){
              add_post_meta($product_ID, '_price',         $precoDesconto );
          }else{
              add_post_meta($product_ID, '_regular_price', $preco );
              add_post_meta($product_ID, '_price',         $precoDesconto );
              add_post_meta($product_ID, '_sale_price',    $precoDesconto );
          }


          add_post_meta($product_ID, '_sku',           $sku );
          add_post_meta($product_ID, '_weight',        $peso );
          add_post_meta($product_ID, '_length',        $comprimento );
          add_post_meta($product_ID, '_width',         $largura );
          add_post_meta($product_ID, '_height',        $altura );
          add_post_meta($product_ID, '_stock',         $this->estoque($estoque) );
          add_post_meta($product_ID, '_idERP',         $idERP ); //ID from erp
          wp_set_object_terms( $product_ID,  'variable', 'product_type' );
          //wp_set_object_terms( $product_ID, $categorias, 'product_cat');

          $guardaVariacoes = array();$i = 1;
          foreach($variacoes as $v){
            $vid = wp_insert_post(
                array(
                  'post_title'    => 'Variacao #' . $i,
                  'post_name'     => 'product-' . $product_ID . '-variation-' . $i,
                  'post_status'   => 'publish',
                  'post_parent'   => $product_ID,
                  'post_type'     => 'product_variation',
                  'guid'          =>  home_url() . '/?product_variation=product-' . $product_ID . '-variation-' . $i
                )
            );

            if( $v[1] == $v[2] ){
                update_post_meta( $vid, '_regular_price', $v[1]);
            }else{
                update_post_meta( $vid, '_price', $v[2] );
                update_post_meta( $vid, '_regular_price', $v[1]);
                update_post_meta( $vid, '_sale_price',  $v[2] );
            }

            update_post_meta( $vid, '_stock', $this->estoque($v[0]) );
            update_post_meta( $vid, '_weight', $v[3]);
            update_post_meta( $vid, '_width', $v[4]);
            update_post_meta( $vid, '_height', $v[5]);
            update_post_meta( $vid, '_length', $v[6]);
            update_post_meta( $vid, '_sku', $v[8]);
            update_post_meta( $vid, '_idERP', $v[9]);

            foreach($v[7] as $nAtr=>$vAtr){
                $nomeAtributo = strtolower(trim($nAtr));


                 $tt = $nomeAtributo;
                 if(strtolower($tt) == 'tamanho')$tt = 'pa_tamanho';
                 if(strtolower($tt) == 'cor')$tt = 'pa_cor';


                update_post_meta( $vid, 'attribute_'.$tt, trim($vAtr));
                $temp = $tt.'|'.$nAtr;
                if( !array_key_exists($temp,$guardaVariacoes) ) $guardaVariacoes[$temp] = array();
                $guardaVariacoes[$temp][] = $vAtr;  
            }
            $i++;
          }

          $product_attributes = array();
          foreach($guardaVariacoes as $r=>$s){

              $r = explode('|',$r);

              $temp = array();
              foreach($s as $w){

                  $w = trim($w);

                  if( strtoupper($w) == 'UNICA'  ){
                      $w = 'Única';
                  }
                  if( strtoupper($w) == 'UNICO'  ){
                      $w = 'Único';
                  }


                  if( array_search( $w,$temp)===false){
                     if( strtoupper(trim($r[1])) == 'COR'){
                         $temp[] = ucfirst(strtolower($w)); 
                      }else{
                          $temp[] = $w; 
                    } 
                  }
              }
              $s = array_unique($temp);



             $tt = $r[1];
             if(strtolower($tt) == 'tamanho')$tt = 'pa_tamanho';
             if(strtolower($tt) == 'cor')$tt = 'pa_cor';


              $product_attributes[$r[0]] = array(
                'name' => $tt, 
                'value' => implode(' | ', $s ),
                'position' => 1,
                'is_visible' => 1,
                'is_variation' => 1,
                'is_taxonomy' => 1  //MY PROBLEM IS HERE
              );
          }
          update_post_meta($product_ID, '_product_attributes', $product_attributes);
        }
        return $product_ID;
    }

当我改变代码时......

    'is_taxonomy' => 1

...它有效,但它不适用于“搜索分层过滤器”,这意味着我必须使用分类法。

如何在不丢失产品内的“属性”的情况下做到这一点?

1 个答案:

答案 0 :(得分:1)

听起来像你正试图为产品设置类别,如果我错了请纠正我。如果是这种情况,您不想使用分类法。首先,您缺少大量产品的meta_key及其所有变体。我建议你在Wordpress的新副本上安装一个新的WooCommerce插件副本。在后端手动创建产品,包含2种版本,并查看wp_postswp_postmetapost_idmeta_keymeta_values) 。对于变体,wp_postmeta表中的实际产品ID的值多于变体的值。 _max_variation_sale_price_id_max_variation_sale_price_min_variation_sale_price_id_min_variation_sale_price等等。还有另一个序列化数组_default_attributes,您可以将其设为空对产品进行数组和序列化,使其具有默认设置。

因此,如果您要引用类别并希望将产品分配到类别,以便您可以单击某个类别并在其中查看该产品...而不是执行以下操作:

is_taxonomy设置为0 is_visible无关紧要,如果你想在附加信息下看到它,而不是设置为1,否则,它仍应显示所有不同的变体,但我想这取决于你的主题的方式处理这个。 position需要从1开始并每次递增,因此请使用变量,例如:

$position = 1;
foreach($guardaVariacoes as $r=>$s) {

    // your top code... down to where the _product_attributes array begins...

    $product_attributes[$r[0]] = array(
        'name' => $tt, 
        'value' => implode(' | ', $s),
        'position' => $position,
        'is_visible' => count($s) > 1 ? 0 : 1,
        'is_variation' => count($s) > 1 ? 1 : 0,
        'is_taxonomy' => 0
    );

    $position++;
}

要为您使用的产品动态创建和分配类别:term_exists(如果术语不存在则返回0或NULL,您可以查看empty()),{{3 (如果术语不存在),插入它以便您可以将类别分配给产品。如果您要将子品牌类别插入父品牌类别,请参阅下面的示例,只是我如何向产品添加类别的示例(wp_term_relationships表格通过产品/帖子ID值为每个产品分配类别) :

// Check if Brand exists or not...
$brand = term_exists('brand', 'product_cat', 0);
$category = 'new category';
$cat_name = addslashes(ucwords(strtolower($category)));
$cats['brand'] = array(
    'name' => $cat_name,
    'slug' => sanitize_title_with_dashes($category)
);

if (!empty($brand))
{
    $subbrand = term_exists($cats['brand']['slug'], 'product_cat', $brand['term_id']);

    if (empty($subbrand))
    {
        $subbrand = wp_insert_term(
            $cats['brand']['name'],
            'product_cat',
            array(
                'slug' => $cats['brand']['slug'],
                'parent'=> $brand['term_id']
            )
        );
    }
} else {

    $brand = wp_insert_term(
        'Brand',
        'product_cat',
        array(
            'slug' => 'brand',
            'parent'=> 0 // This means it will be at the first level!
        )
    );

    $subbrand = term_exists($cats['brand']['slug'], 'product_cat', $brand['term_id']);

    if (empty($subbrand))
    {
        $subbrand = wp_insert_term(
            $cats['brand']['name'],
            'product_cat',
            array(
                'slug' => $cats['brand']['slug'],
                'parent'=> $brand['term_id']
            )
        );
    }
}

$categories = array(
    'product_id' => // put the product id value in here!
    'terms' => array()
);

if (!empty($subbrand))
{
    $categories['terms']['subbrands'] = $subbrand;
}

// Now insert into term_relationships table for that product and that's all folks...
foreach($categories['terms'] as $type => $nfo)
{
    $wpdb->insert(
        $wpdb->prefix . "term_relationships", 
        array(
            'object_id' => $categories['product_id'], 
            'term_taxonomy_id' => intval($nfo['term_taxonomy_id']),
            'term_order' => 0
        ),
        array('%d', '%d', '%d')
    );
}

因此,希望这可以帮助您为您的产品构建类别,同时仍然在搜索过滤器中保持您的产品属性。祝你好运。