如何从WordPress中的产品类别名称获取css ID


How to get css ID from product category name in Wordpress

我正在使用woocommerce作为目录。我想从类别 ID 中为每个产品类别提供 css ID。因为我想在某个地方制作"显示:无"。

我的代码在Chrome控制台中查找如下:

<div class="woo-category">
  <span>
    <a href="http://www.yazicimakina.com.tr/?product_cat=overlap" rel="tag">Overlap</a>
    ","
    <a href="http://www.yazicimakina.com.tr/?product_cat=tam" rel="tag">TAM</a>
    ","
    <a href="http://www.yazicimakina.com.tr/?product_cat=tumu" rel="tag">TÜMÜ</a>
  </span>
</div>

我的PHP代码:

<div class="woo-category">
  <?php
    $postid = get_the_ID();
    $categories = get_the_term_list($postid, 'product_cat', '', ', ', '');
    ?>
    <span><?php print_r($categories); ?></span>
 </div>

我想:

<div class="woo-category">
  <span>
    <a id="example1" href="http://www.yazicimakina.com.tr/?product_cat=overlap" rel="tag">Overlap</a>
    ","
    <a id="example2" href="http://www.yazicimakina.com.tr/?product_cat=tam" rel="tag">TAM</a>
    ","
    <a id="example3" href="http://www.yazicimakina.com.tr/?product_cat=tumu" rel="tag">TÜMÜ</a>
  </span>
</div>

我认为方法是:打印到类别 id 作为 css id,但我不知道如何在 PHP 中做到这一点。

这里的最佳实践是自定义循环。尝试以下操作

<?php
$terms = get_the_terms( $post->ID, 'product_tag' );
if ($terms && ! is_wp_error($terms)): ?>
    <?php foreach($terms as $term): ?>
        <a href="<?php echo get_term_link( $term->slug, 'product_tag'); ?>" rel="tag" class="<?php echo $term->slug; ?>"><?php echo $term->name; ?></a>
    <?php endforeach; ?>
<?php endif; ?>