get_field() 不返回分类数据(高级自定义字段)
Posted
技术标签:
【中文标题】get_field() 不返回分类数据(高级自定义字段)【英文标题】:get_field() returns no data (advanced custom fields) on taxonomy 【发布时间】:2021-02-24 23:04:42 【问题描述】:我已经在分类“课程类别”上创建了一个自定义字段,并且我已经从管理面板添加了值,我希望将此自定义字段放到课程模板页面上。我在课程模板php文件中写了下面的代码
$categories= get_the_category();
print_r($categories);
if (!empty($categories))
$term_id = $categories[0]->term_id;
echo "ok";
print_r($term_id);
$app_certification1 = get_field('app_certification','term_'.$term_id);
print_r($app_certification1);
PS: above print($term_id) 打印出下面
Array ( [0] => WP_Term Object ( [term_id] => 315 [name] => Accountants [slug] => accountants [term_group] => 0 [term_taxonomy_id] => 315 [taxonomy] => category [description] => [parent] => 0 [count] => 8 [filter] => raw [cat_ID] => 315 [category_count] => 8 [category_description] => [cat_name] => Accountants [category_nicename] => accountants [category_parent] => 0 ) [1] => WP_Term Object ( [term_id] => 281 [name] => Book Keepers [slug] => book-keepers [term_group] => 0 [term_taxonomy_id] => 281 [taxonomy] => category [description] => [parent] => 0 [count] => 8 [filter] => raw [cat_ID] => 281 [category_count] => 8 [category_description] => [cat_name] => Book Keepers [category_nicename] => book-keepers [category_parent] => 0 ) [2] => WP_Term Object ( [term_id] => 247 [name] => Xero Practice Manager [slug] => xpm [term_group] => 0 [term_taxonomy_id] => 247 [taxonomy] => category [description] => [parent] => 0 [count] => 22 [filter] => raw [cat_ID] => 247 [category_count] => 22 [category_description] => [cat_name] => Bero C anager [category_nicename] => xpb [category_parent] => 0 ) )
我想要实现的是以下结果(即 https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/),但在课程页面而不是课程类别页面上。
print_r($app_certification1);
在这个阶段没有打印任何东西,我参考了很多文档、论坛来获得上述解决方案,我觉得它非常接近正确答案。非常感谢任何帮助
【问题讨论】:
get_the_category() 是 get_the_term($term,'category') 的别名函数;所以试着用它作为你的分类学slug @AliQorbani 谢谢它会解决问题吗? 你应该尝试让我知道它是否有效 我刚刚完成并可以打印 wp_term 对象,下一步是打印出该字段这是对象 - WP_Term 对象([term_id] => 247 [name] => Xero实践经理 [slug] => xpm [term_group] => 0 [term_taxonomy_id] => 247 [taxonomy] => category [description] => [parent] => 0 [count] => 22 [filter] => raw ) ,我可以用上面的对象来做吗 get_field() 仅适用于帖子:advancedcustomfields.com/resources/get_field 【参考方案1】:在上面的cmets的帮助下,我确实成功实现了它下面是代码sn-p。(这里ld_course_category是指learndash课程类别,我之前使用'category'是错误的)
$gotTerms=get_the_terms( $post->ID , 'ld_course_category' );
然后我写了(app_logo 是添加到课程类别的自定义字段)
$applogo = get_field('app_logo', $gotTerms[0]);
echo $applogo;
就像上面的 app_logo 一样,我继续使用其他字段..
希望有人觉得这很有帮助。:)
【讨论】:
以上是关于get_field() 不返回分类数据(高级自定义字段)的主要内容,如果未能解决你的问题,请参考以下文章
PHP if/else get_field() 与 WordPress