将多个类别分配为 wordpress 中自定义帖子类型的类

问题描述

我已经设置了一些自定义帖子类型,并且正在尝试使用 javascript 实现页面过滤。我设法能够输出已签名的第一个类,但我无法让它添加多个类。理想情况下,我不想对类别进行硬编码,因为我会将其交给客户,他们将来会添加更多。

这是我目前所拥有的:

<?PHP
    $loop = new WP_Query( array(
        'post_type' => 'portfolio_item','order' => 'ASC','posts_per_page' => -1
        )
    );
     while ( $loop->have_posts() ) : $loop->the_post();
         $cats = wp_get_post_categories($post_id);
                
            
            echo '<div class="'.implode(" ",$cats).' filter-item pb-3">';
        ?>
    <div class="p-4 border text-center bg-white h-100 rounded">
         <a href="<?PHP echo the_permalink();?>">
              <div class="dealer-logo" style="height: 300px">
                  <img src="<?PHP echo get_the_post_thumbnail_url($post_id,'full'); ?>"
                       class="mb-4 mx-auto object-fit object-cover" style="height: 300px">
              </div>
              <h3><?PHP echo the_title(); ?></h3>                       
              <div class="mt-4 pb-3">
                   <p>Read More</p>
              </div>
            </a>


       </div>
   </div>

 <?PHP endwhile;?>

例如,在顶部的“过滤器项目”div 中,我希望看到 2/3 属于该自定义帖子类型的类填充。

我目前只获得与帖子相关的第一个课程。我想我需要将类别放在一个数组中,然后遍历这些类别。然而,这有点超出我的范围。

非常感谢任何帮助!

解决方法

正如您所提到的,您需要在数组中获取帖子类别。使用 wp_get_post_categories function

一旦您在数组中有类别,请使用它。

    $cats = array('one','two','three');
    echo '<h2 class="'.implode(" ",$cats).'">Test</h2>';

这会让你得到你想要的。