首页 > 解决方案 > PHP - 获取 CPT 分类,从 ACF 显示分类颜色

问题描述

我正在使用 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;"

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

标签: phpwordpresscustom-post-typecustom-taxonomy

解决方案


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

    $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;"

推荐阅读