显示应用于父类别上的子类别的 WooCommerce 的高级自定义字段



我设置了一个高级自定义字段,显示在woocommerce子类别上,允许用户通过颜色选择器字段定义颜色。

此字段会将该颜色应用于与该子类别相关的许多元素(设置子类别缩略图的样式、产品页面本身等(。

我目前正在根据 ACF 文档使用此代码来拉入字段并将其显示在子类别页面上:

$term = get_queried_object();
$color = get_field('colour', $term); // Get ACF Field

这工作正常,直到涉及到子页面的父类别。我无法为父项的子类别调用该字段。我知道我需要使用 get_terms((。不过,我无法让它工作。

这是我找到的一些代码,我已将其添加到内容product_cat.php循环中。然而,它只是打破了 woocommerce 循环。我需要对此代码执行哪些操作才能使父类别页面显示所有子子类别,每个子类别及其相关的颜色字段?

// current term
$current_term = get_queried_object();
// child terms
// this returns an array of terms
$args = array(
  'taxonomy' => 'YOUR TAXONOMY HERE',
  'parent' => $current_term->term_id,
  // you may need other arguments depending on your needs
);
$child_terms = get_terms($args);
// you need to maybe loop through the child terms gotte
// to pick which one you want to use
// I'm assuming that you only want to use the first one
$child_term = false; // set it to false to begin with
                     // we'll use this later
if ($child_terms) {
  $child_term = $child_terms[0];
}
// make a decision
if ($child_term) {
  // get field value(s) from child term
  $color = get_field('color', $child_term);
} else {
  // get field value(s) from current term
  $color = get_field('color', $current_term);
}
// do something with the values
echo $color; 

我在这里找到了解决方案:https://wordpress.stackexchange.com/a/341632

add_action('woocommerce_after_subcategory_title', 'wpse_add_custom_text_under_category_title', 10);
function wpse_add_custom_text_under_category_title($category) {
   $term_id = 'product_cat_'.$category->term_id;
   the_field('krotki_opis_kategorii', $term_id);
}

来自亚历克斯·乌勒伯格:get_queried_object_id商店存档页面上,它将返回页面的 ID,而不是类别。当您使用钩子时,$category对象将通过钩子传入。

最新更新