【问题标题】:PHP - Get CPT taxonomy, show taxonomy color from ACFPHP - 获取 CPT 分类,从 ACF 显示分类颜色
【发布时间】:2018-11-25 05:34:12
【问题描述】:

我正在使用 Wordpress 的 WP Job Manager 插件,它本质上是基于自定义帖子类型构建的。它启用了类别,我为每个类别分配了一种颜色。

我可以使用类似的方法来显示颜色:

<div style="background-color:<?php the_field('job_category_colour', 'category_54'); ?>; height: 100px; width: 100px;"></div>

但这不是很好,因为我将此代码添加到 single.php 页面,所以我需要它足够动态以首先检查帖子的类别,然后应用该帖子的颜色。

我可以使用这个来拉出一个类别列表:

<?php the_terms( $post->ID, 'job_listing_category'); ?>

所以,我想我必须以某种方式将两者结合起来 - 这就是我卡住的地方......

它本质上需要说;

'获取类别'

'获取该类别的颜色'

'将该颜色作为背景色应用到 div'

我尝试了以下各种格式:

style="background-color:<?php the_field('job_category_colour', '$post->ID, 'job_listing_category''); ?>; height: 100px; width: 100px;"

但我似乎无法让它全部正常工作。任何帮助或建议将不胜感激 - 感谢您的关注! :)

【问题讨论】:

  • 您忘记了帖子 ID '$post->ID' 中的单引号,并且 job_listing_category 有额外的单引号将其删除。
  • 谢谢 dipmala - 你的意思是这样的:
    - 因为那仍然无法正常工作...
  • 您需要先获取分类,然后在 the_field 中使用该 id
  • 我知道,这似乎是我做不到的,因此是原帖:)
  • 检查@shaun 答案如下。

标签: php wordpress custom-post-type custom-taxonomy


【解决方案1】:

请检查以下代码是否相同。

    $term_list = wp_get_post_terms($post->ID, 'job_listing_category', array("fields" => "all"));
    $currentcolor='';
    foreach($term_list as $term_single) 
    {
        $termid= $term_single->term_id; 
        $colorvalue= get_field('job_category_colour',  'category_' . $termid);
        if($colorvalue!='')  $currentcolor =$colorvalue;
    }


    style="background-color:<?php echo $currentcolor ; ?>; height: 100px; width: 100px;"

【讨论】:

  • 非常感谢,dipmala!这完美!但是,如果帖子分配了多个类别,它将不起作用,但老实说,这是一种设计/组织问题 - 再次感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多