在Wordpress中检查所选帖子是否属于类别

时间:2019-06-10 15:58:01

标签: wordpress

我想检查我选择的帖子是否属于我也在帖子页面上显示的类别之一。如果帖子属于我的类别之一,那么我想为类别的标题添加一种样式(颜色:红色;)。因此,我创建了下一个代码:

 <?php
$arg = array(
    'orderby'       => 'name',
    'order'         => 'ASC',
    'post_type'     => 'product',
    'post_per_page' => 12,
    'taxonomy'      => 'product_cat',
);
$categories = get_categories($arg);
$post_id = get_the_ID();

?>
<?php foreach ($categories as $category) : ?>
    <a href="<?php echo get_category_link($category); ?>" class="test">
        <span class="name"><?php echo $category->name; ?></span>
    </a>
    <?php $x =$category->term_id  ?>
    
}
 ?>
<?php endforeach; // $categories as $category ?>
 
 
 
 

我得到了职位ID和类别ID,但是我无法获得想要的东西。我认为可能应该使用in_category。谁知道如何解决问题?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

  1. 在主CSS文件中创建具有所需样式的CSS类

    .red {
    color: red;
    }
    
  2. 调整您的for循环,以包含一个变量,该变量包含要检查的类别的ID或ID数组。以及当前的类别ID。另外,添加一个带有空字符串的变量,我们以后可以将其用作类添加到您的跨度中。

    $current_cat_id = $category->term_id;
    $check_cat_id = array(122,178); // Add the ID or IDs of the categories you want to check against
    $red_class = ''; // An empty string var we'll use for the span class below
    
  3. 然后对照术语ID数组检查当前发布的术语ID。如果它存在于数组中,则将类变量更改为CSS类名。

    /* Check to see if the current cat ID matches to the one you want to check for */
    
      if (in_array($current_cat_id, $check_cat_id)) {
    
        // Put the class name of the CSS class you create as this string
    
        $red_class = 'red'; 
    
      } 
    
  4. 最后,在您的跨度上回显class变量。如果IF语句为true,它将回显您的类名,如果不是,则不会将该类添加到范围中。

    <span class="name <?php echo $red_class; ?>"><?php echo $category->name; ?></span>
    

这是整个事情:

    <?php
    $arg = array(
    'orderby'       => 'name',
    'order'         => 'ASC',
    'post_type'     => 'product',
    'post_per_page' => 12,
    'taxonomy'      => 'product_cat',
    );

    $categories = get_categories($arg);
    $post_id = get_the_ID();

    ?>

    <?php foreach ($categories as $category) : ?>

     $current_cat_id = $category->term_id;
     $check_cat_id = array(122); // Add the ID or IDs of the categories you want to check against
     $red_class = ''; // An empty string var we'll use for the span class below

/* Check to see if the current cat ID matches to the one you want to check for */

     if (in_array($current_cat_id, $check_cat_id)) {

        // Put the class name of the CSS class you create as this string

        $red_class = 'red'; 
     }

    <a href="<?php echo get_category_link($category); ?>" class="test">

    /* Echo the red_class var in the span class so that if it's matched it will have the class you assign */

    <span class="name <?php echo $red_class; ?>"><?php echo $category->name; ?></span>
    </a>


   }
   ?>
   <?php endforeach; // $categories as $category ?>