【问题标题】:WordPress/ACF: get_category(); for parent categoryWordPress/ACF: get_category();对于父类别
【发布时间】:2020-12-29 21:32:09
【问题描述】:

我使用ACF Wysiwyg Editor field 以便能够为我的类别页面编写一些额外的文本。我正在使用 category.php 呼应文本

起初我以为我可以直接回显 get_field,但发现我需要传入类别。因此我使用了 get_the_category()。但由于某种原因,代码仅适用于子类别:

example.com/category/parent/child/

我也试过 wp_get_post_categories();但没有运气。我错过了什么??

<?php

$category = get_the_category();

$extra_text = get_field('ekstra_tekstfelt', $category[0] );
?>

<p> <?php echo $extra_text ?></p>

我尝试了 print_r($category) ,其中子类别和父类别都给了我一个数组:

儿童类别

Array ( [0] => WP_Term Object ( [term_id] => 27 [name] => Tilbehør [slug] => tilbehor [term_group] => 0 [term_taxonomy_id] => 27 [taxonomy] => category [description] => [parent] => 1 [count] => 31 [filter] => raw [cat_ID] => 27 [category_count] => 31 [category_description] => [cat_name] => Tilbehør [category_nicename] => tilbehor [category_parent] => 1 ) )

父类别

Array ( [0] => WP_Term Object ( [term_id] => 46 [name] => Bagværk [slug] => bagvaerk [term_group] => 0 [term_taxonomy_id] => 46 [taxonomy] => category [description] => [parent] => 1 [count] => 16 [filter] => raw [cat_ID] => 46 [category_count] => 16 [category_description] => [cat_name] => Bagværk [category_nicename] => bagvaerk [category_parent] => 1 ) [1] => WP_Term Object ( [term_id] => 16 [name] => Dessert [slug] => dessert [term_group] => 0 [term_taxonomy_id] => 16 [taxonomy] => category [description] => [parent] => 1 [count] => 22 [filter] => raw [cat_ID] => 16 [category_count] => 22 [category_description] => [cat_name] => Dessert [category_nicename] => dessert [category_parent] => 1 ) )

【问题讨论】:

  • 首先要注意的是,您应该在这里使用get_field() 而不是the_field(),因为the_field() 实际上会立即回显,因此在您尝试保存变量时不使用它。还有 - get_the_category 缺少它的 () 并且通常用于帖子对象 - 您可以尝试使用 get_queried_object() 来尝试获取类别对象。
  • 还有 - 您确定父猫已填写该字段吗?它是否使用相同的 cat 文件?还是使用archive.php?
  • 谢谢你,斯坦德。我的道歉。我正在使用 get_field 和 get_the_category();... get_queried_object 破坏了站点并给了我错误。我刚刚在 category.php 上尝试了一个简单的回显,它在父猫和子猫上都出现了。是的,父猫已经填写了该字段。
  • 弄清楚为什么 get_queried_object();正在破坏网站...因为我使用的是 $category[0] - 已删除 [0] 并且它给了我相同的结果:适用于子类别但不适用于父类别。

标签: php wordpress categories advanced-custom-fields wysiwyg


【解决方案1】:

通过您的代码,似乎没问题,但需要检查我们是否获取每个变量的值,acf 字段是否为空?

以下是 ACF 官方网站的示例。在你的代码中,你可以确保你得到了你传递的第二个参数的正确对象。

 // get the current taxonomy term
 $term = get_queried_object(); // or other way where you get the category term object
 // example
 $image = get_field('image', $term);
 $color = get_field('color', $term);
 echo $color;
 echo $image;

【讨论】:

  • 谢谢!我试过 get_queried_object();但结果相同...适用于子类别但不适用于父类别:/
  • 尝试打印对象。您是否正在获取具有正确数据的对象?
  • 在您的代码中,尝试为子类别和父类别打印$category
  • 两者都给了我一个数组...我已经更新了问题:)
  • 我会要求尝试像这样$taxonomy . '_' . $term_id。例如category_123,而不是传递术语对象
猜你喜欢
  • 1970-01-01
  • 2014-08-29
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多