【问题标题】:Woocommerce multisite network => get attribute terms of products from other blog idWoocommerce 多站点网络 => 从其他博客 ID 获取产品的属性术语
【发布时间】:2020-10-12 14:59:12
【问题描述】:

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

在 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 访问属性吗?

【问题讨论】:

  • 现在可以了。我认为重复术语 slug 存在问题(但它们仍然被分配到不同的分类,......嗯?)

标签: wordpress woocommerce attributes multisite


【解决方案1】:

即使在我从博客切换分类法之后,我也遇到了同样的问题,以您的示例为例,博客 #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();

【讨论】:

    猜你喜欢
    • 2020-11-02
    • 2021-05-22
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2018-10-09
    相关资源
    最近更新 更多