skip to Main Content

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


  1. You can use the ‘search’ or ‘name_like’ fields in the first argument array, per the wordpress documentation here:

    https://developer.wordpress.org/reference/classes/wp_term_query/__construct/

    For example, say you want to get all terms where the name contains ‘foo’

    <?php 
    $terms = get_terms(array(
        'taxonomy' => 'product_tag', 
        'hide_empty' => false,
        'name__like' => '%foo%'
    )); 
    
    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search