【问题标题】:Woocommerce tag list having specific string具有特定字符串的 Woocommerce 标签列表
【发布时间】:2020-08-22 14:44:18
【问题描述】:

该代码非常适合列出 WooCommerce 产品标签,但我想用它添加一个查询。

我只想列出包含特定字符串的产品标签。

<?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>

【问题讨论】:

    标签: php wordpress woocommerce taxonomy taxonomy-terms


    【解决方案1】:

    根据此处的 wordpress 文档,您可以在第一个参数数组中使用 'search' 或 'name_like' 字段:

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

    例如,假设您要获取名称中包含“foo”的所有术语

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

    【讨论】:

    • 什么意思?你试过什么?请在您的问题中发布代码。
    • &lt;?php $terms = get_terms(array( 'taxonomy' =&gt; 'product_tag', 'hide_empty' =&gt; false, 'name_like' =&gt; '%foo%' )); $count = count($terms); echo "found ". $count . " Records"; ?&gt; &lt;div class="product-tags"&gt; &lt;ul&gt; &lt;?php foreach ( $terms as $term ) { ?&gt; &lt;li&gt;&lt;a href="&lt;?php echo get_term_link( $term-&gt;term_id, 'product_tag' ); ?&gt; " rel="tag"&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;/div&gt;
    • 你真的有任何名称中包含“foo”这个词的产品标签吗?您需要将 foo 更改为您的查询。
    • 添加一个额外的下划线并使用变量解决了这个问题.. 'name__like' => $string, ...感谢您的支持..
    【解决方案2】:

    使用WP_Term_Query 代替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;
    }
    

    【讨论】:

    • 工作.. 但我想找到总数。也返回了行数。以前使用过$count = count($terms);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多