Woocommerce多站点网络=>从其他博客ID获取产品的属性条款

问题描述

我们有一个带有两个woocommerce商店的多站点Worpdress安装。

在blog_id 2中,我们需要从blog_id 1中获得一些具有其属性值(pa_testattr)的产品。 效果很好,到目前为止,我们已经获得了所需的产品,产品名称和图像。 但是我们没有从pa_testattr配属中获得这些产品的属性值/术语来显示

这是我们拥有的代码

switch_to_blog(1); 

$args = array(
    'post_type' => 'product','category' =>  'my_cat','orderby'  => 'name','order'  => 'ASC','posts_per_page' => 10 
);

foreach( wc_get_products($args) as $product ){
    $product_id = $product->get_id();
    // echo  $product_id.'<br>';

// THIS DOES NOT WORK 
foreach( wc_get_product_terms( $product_id,'pa_testattr' ) as $attribute_value ){
   echo $attribute_value . '<br>';
}
// THIS DOES NOT WORK 


// THIS DOES ALSO NOT WORK  (Output empty: string(0) "")
$myattr = $product->get_attribute( 'pa_testattr' );
var_dump($myattr);
// THIS DOES ALSO NOT WORK  (Output empty: string(0) "")

echo '<p>' . $product->get_name() . '</p>';
echo $product->get_image();


}


restore_current_blog();

错误在哪里?难道我们要从另一个博客ID访问属性

解决方法

我遇到了同样的问题,即使在我切换博客分类后,以您的示例为例,博客 #1 在博客 #2 中不可用。我的解决方案是暂时诱使 WordPress 认为存在分类法,从而允许您访问术语。

switch_to_blog(1);

// get the global taxonomies object...
global $wp_taxonomies;

// trick Wordpress into thinking 'pa_testattr' is a value taxonomy on blogs other than #1
// so we don't get the 'Invalid Taxonomy' error
if (!array_key_exists('pa_testattr',$wp_taxonomies)) {
  register_taxonomy(
    'pa_testattr',array(
      'product',),array(
      'hierarchical' => true,)
  );
  $added_temp_taxonomy = true;
} else {
  $added_temp_taxonomy = false;
}

// get terms,for example
$tags = get_terms( array(
  'taxonomy' => 'pa_testattr','hide_empty' => true,) );

// do what you need to do with them...

// remove the taxonomy if it was added temporarily 
if ($added_temp_taxonomy) {
  unregister_taxonomy('pa_testattr');
}

restore_current_blog();