通过 slug 为 foreach 循环 Woocommerce 排除类别

Exclude category by slug for foreach loop Woocommerce

我试图从我的循环中删除一个名为“outlet”的产品类别术语 slug,我看到了这个 post

我在我的代码中尝试过,但我遗漏了一些东西,有没有办法删除特定的产品类别?

<?php
  $get_parents_cats = array(
    'taxonomy' => 'product_cat',
    'parent'   => 0,
    'number'       => '9',
    'hide_empty' => false,
    'tax_query' => array(
         'taxonomy' => 'category',
         'field'    => 'slug',
         'terms'    => array( 'outlet' ),
         'operator' => 'NOT IN',
    ),
  );

  $categories = get_categories( $get_parents_cats );
  
  foreach ($categories as $cat) {
    $cat_id   = $cat->term_id;
    $cat_link = get_category_link( $cat_id );
    $term_link = get_term_link( $cat->term_id );
    
    $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true ); // Get Category Thumbnail
    $image = wp_get_attachment_url( $thumbnail_id ); 
    if ( $image ) {?>
  
    <div class="wrapper">
        <img src="<?php echo $image; ?>"/>
        <a href="<?php echo get_term_link($cat->slug, 'product_cat') ?>">
        <div class="title">
            <h3><?php echo $cat->name; ?></h3>
        </div>
        </a>
    </div>
    
  
    <?php
    }
    wp_reset_query();} 
  ?>

您的代码中存在一些错误和缺失。请尝试以下操作:

<?php
$taxonmomy     = 'product_cat';
$exclude_slug  = 'outlet';
$exclude_id    = $term_name = get_term_by( 'slug', $exclude_slug, $taxonmomy )->term_id; // term Id to be excluded

// Get the array of top level product category WP_Terms Objects 
$parents_terms = get_terms( array(
    'taxonomy'   => $taxonmomy,
    'parent'     => 0,
    'number'     => 9,
    'hide_empty' => 0,
    'exclude'    => $exclude_id,
) );

// Loop through top level product categories
foreach ($parents_terms as $term) {
    $term_id   = $term->term_id;
    $term_name = $term->name;
    $term_link = get_term_link( $term, $taxonmomy );
    $thumb_id  = get_woocommerce_term_meta( $term_id, 'thumbnail_id', true ); // Get term thumbnail id

    // Display only product categories that have a thumbnail
    if ( $thumb_id > 0 ) :
        $image_src = wp_get_attachment_url( $thumb_id ); // Get term thumbnail url
    ?>
    <div class="wrapper">
        <img src="<?php echo $image_src; ?>"/>
        <a href="<?php echo $term_link ?>">
            <div class="title">
                <h3><?php echo $term_name; ?></h3>
            </div>
        </a>
    </div>
    <?php
    endif;
}
?>

已测试并有效。