PHP Woocommerce 获取产品品牌名称

PHP Woocommerce get product brand name

我创建插件并想从 woocommerce 获取品牌名称。 在第一次我 post 产品 1 号插件它的工作和获得产品品牌如我所愿但是当我创建产品 post 2 号和 3 号从品牌名称获得从产品 1 号

怎么了?

if ( class_exists( 'WooCommerce' ) ) {
        $kode = $product->get_sku();
        $terms = wp_get_post_terms( $product_id, 'brand', array('orderby'=>'name'));

        $brands = get_terms( 'brand', array(
        'orderby'       => 'name'
        //,'product__in'  => $product->id
        // orderby arguments ('name', 'slug','term_group', 'term_id', 'id', 'description')
        ) );

        foreach ( $brands as $key => $brand ) :
            $brand_name = $brand->name;
        endforeach;

        $merk = $brand_name;

        //this i want to print the brand name
        echo "<strong>STOCK ".$merk." ".$kode."</strong><br/>";


    } else {
      echo "please active your WooCommerce plugin.";
    }

如果你想从产品中获取条款,你应该试试这个:

$terms = wp_get_post_terms( $product_id, 'brand', array('orderby'=>'name'));
//you could use: var_dump($terms); to see what it is.

如果你想连接你的品牌名称,你可以这样做:

$term_names = wp_get_post_terms( $product_id, 'brand', array('orderby'=>'name', 'fields' => 'names'));
$term_names = implode(' ', $term_names);
echo $term_names;

更新代码:

foreach ( $brands as $key => $brand ) :
    echo "<strong>STOCK ".$brand->name." ".$kode."</strong><br/>";
endforeach;

echo 必须在 foreach 循环内。

这应该适合你。

if ( class_exists( 'WooCommerce' ) ) {
        $kode = $product->get_sku();

        $tax = array(
        'STOCK'=>'brand',
         );

        foreach ($tax as $mk_label => $mk_value) {
            $make_array = wp_get_post_terms(get_the_ID(), $mk_value, array("fields" => "names"));
            foreach ($make_array as $value) {
                $mk .= $value.", ";
            }
            echo '<strong>'.$mk_label.' <a href="javascript:void(0)">'.rtrim($mk,", ").' '.$kode.'</a></strong>';
            $mk ="";
        }


    } else {
      echo "please active your WooCommerce plugin.";
    }

我们正在根据当前产品 ID 动态获取术语并相应地获取品牌。如果您需要更多帮助,请告诉我。

谢谢

而不是分类 "brand",它应该是 "pa_brand"。

$term_names = wp_get_post_terms( $product_id, 'pa_brand', array('orderby'=>'name', 'fields' => 'names'));