Wordpress如何从父类别中获取字段

Wordpress how to get field from parent category

我正在尝试在子类别归档页面的自定义字段中显示图像。

当前设置是:

<?php
    $term_id = get_queried_object()->term_id;
    $post_id = 'product_cat_'.$term_id;
    $custom_field = get_field('brand_background', $post_id);
?>

<div id="brandHeader" class="brand-header-logo" style="background-image: url('<?php the_field('brand_background', $post_id); ?>');">

这显然是从当前所在的类别存档中获取 'background image' 字段。

如果类别是子类别,我希望能够从父类别中提取 'background image'。我已经尝试了一些方法,但似乎没有用 - 有人可以帮忙吗?

您可以使用 get_ancestors 函数获取 parent id 并使用该 ID 获取您的字段:

get_ancestors

假设您的类别如下所示:

-Parent (id = 24)
--Child (id = 42)

$term_id = get_queried_object()->term_id;

$term_ancestor_ids = get_ancestors($term_id, 'product_cat');

// if you do a print_r on $term_ancestor_ids
// you'll see this: 
// Array ( [0] => 24 )

$post_id = 'product_cat_'.$term_ancestor_ids[0];

$custom_field = get_field('brand_background', $post_id);

已经过测试并且可以正常工作,如果您也能正常工作,请告诉我!