Woocommerce tag list having specific string

Viewed 176

The code works perfectly for listing WooCommerce product tags, but I want to add a query with it.

I would like to list only product tags that contain a specific String.

<?php
$terms = get_terms(array(
    'taxonomy' => 'product_tag', 
    'hide_empty' => false,
));

$count = count($terms);
echo "found ". $count . " Schools";

?>
<div class="product-tags">
    <ul>
    <?php foreach ( $terms as $term ) { ?>
        <li><a href="<?php echo get_term_link( $term->term_id, 'product_tag' ); ?> " rel="tag"><?php echo $term->name; ?></a></li>
    <?php } ?>
    </ul>
</div>
2 Answers

Use WP_Term_Query instead of get_terms

$keyword = 'tag';

// Args
$args = array(
    'taxonomy'    => 'product_tag',
    'hide_empty'  => false,
    'name__like'  => $keyword,
);

// Term Query
$query = new WP_Term_Query($args);

// Get terms
$get_terms = $query->get_terms();

// Count
$count = count( $get_terms );

echo "found ". $count . " Schools";

// Loop
foreach ( $get_terms as $terms ) {
    echo $terms->name;
}
Related