ACF从产品术语中获取图像



我想在我的产品页面上显示一个品牌标志。我使用高级自定义字段(ACF(在分类法"上插入图像;品牌";。

https://snipboard.io/JcYvM4.jpg

我已经尝试了下面的代码,并尝试像这里的页面上那样做,但它不起作用。。。

https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

*图像返回格式是";数组";。

function action_woocommerce_before_variations_form(  ) { 
$queried_object = get_queried_object(); 
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;  

$image = get_field('brand_logo', $taxonomy . '_' . $term_id);
echo '<img src="'.$image['url'].'" />';

}; 

// add the action 
add_action( 'woocommerce_before_variations_form', 'action_woocommerce_before_variations_form', 10, 0 ); 

您可以这样尝试:

<?php
$category_icon = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$category-logo = wp_get_attachment_url( $category_icon );
?> 

在产品页面上调用woococommerce_before_variations_form。

所以,如果你调用get_queried_object()时WordPress会返回产品对象,而不是品牌术语。

所以

  1. 使用Get_the_trms函数获取带有产品id的品牌
  2. 迭代您的品牌并使用get_field函数获取图像
  3. (可选(获取品牌链接
  4. 显示您的图像
<?php 
function prefix_add_brand_before_variations_form() {
// First get brand(s) with your product id. 
$brands = get_the_terms(get_the_id(), 'brand');

// get_the_terms return false or an array, so 
if(!$brands) {
return;
}
foreach ($brands as $brand) {
$image = get_field('brand_logo', $brand);
$brand_url = get_term_link($brand);
if (is_array($image)) : ?>
<a href="<?php echo $brand_url ?>">
<img src="<?php echo $image['url']; ?>" />
</a>
<?php
endif;
}
}
add_action('woocommerce_before_variations_form', 'prefix_add_brand_before_variations_form', 10, 0); 

最新更新