【问题标题】:Display Advanced Custom Field for Woocommerce applied to subcategory on parent category显示适用于父类别子类别的 Woocommerce 高级自定义字段
【发布时间】:2018-04-18 13:42:34
【问题描述】:

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

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

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

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

在涉及子页面的父类别之前,这可以正常工作。我无法为父项的子类别调用该字段。我知道我需要使用 get_terms()。我无法让它工作。

这是我发现的一些代码,已添加到 content-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; 

【问题讨论】:

  • 我对它的了解不够,不知道如何使用它。我受知识限制,寻找示例进行修改
  • 看来我之前的评论是不正确的。看起来您需要术语对象来拉入该字段,而不是术语 id。您的 $args 中是否有 'taxonomy' => 'product_cat', 而不是占位符 'YOUR TAXONOMY HERE'?
  • 是的,产品猫被替换了,它在输入此代码时打破了页面
  • 好的,我对 woocommerce 进行了更多查看,但我不确定如何帮助解决这个特定的模板。只是在这里暗中拍摄,如果您在定义$current_term 并输入var_dump(get_field('color', $current_term)); 后将所有内容注释掉会返回该字段的正确值吗?
  • 只返回NULL

标签: php wordpress woocommerce advanced-custom-fields


【解决方案1】:

我在这里找到了解决方案: 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 对象会通过钩子传入。

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2018-08-26
    相关资源
    最近更新 更多