【问题标题】:I need to get all tags from woo commerce products in a page我需要从页面中的 woocommerce 产品中获取所有标签
【发布时间】:2018-03-23 21:51:56
【问题描述】:

我需要将所有产品标签显示为主页上的下拉菜单。我尝试了以下代码,但没有成功。

$terms = get_terms( 'product_tag' );
$term_array = array();
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        $term_array[] = $term->name;
    }
}

它总是返回一个空数组。有什么建议么?谢谢。

【问题讨论】:

  • 我尝试了该解决方案,但没有成功。
  • 什么是“主页”?
  • 像一个索引页,或主页。就我而言,我尝试在主题 function.php 文件中编写一个函数来获取 woo-commerce 产品的所有标签。我可以获取 ID、标题和内容,但不能获取标签。下面是我尝试过的另一段代码 sn-p 仍然没有运气:
  • $args = array('post_type' => 'product'); $list_tags = 数组(); $loop = new WP_Query($args); while ($loop->have_posts()) : $loop->the_post(); $terms = get_the_terms(get_the_ID(), 'product_tag');; if (!empty($terms) && !is_wp_error($terms)) { foreach ($terms as $term) { $list_tags = $term->slug; array_push($list_tags, $terms); } } 结束;返回 $list_tags;

标签: wordpress woocommerce


【解决方案1】:

我不确定您所说的dropdown 是什么意思,但我会使用<select> 来回答这个问题。

在你的functions.php中

function get_some_tags_man(){
    $terms = get_terms( array( 
        'hide_empty' => false, // only if you want to hide false
        'taxonomy' => 'product_tag',
     ) 
    );
    $html = '';
    if($terms){
        $html .= '<select name="terms" id="someID">';
        foreach($terms as $term){
            $html .= "<option name='$term->name'>$term->name</option>";
        }
        $html .= '</select>';
    }
    return $html;
}

在您的主题文件中:

<?php echo get_some_tags_man(); ?>

【讨论】:

    【解决方案2】:

    试试这个,它也会显示空标签。

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

    【讨论】:

    • 完美兄弟!像魅力一样工作!
    【解决方案3】:

    我刚刚尝试了代码(在产品页面和商店页面中)并且它有效。 主页您是指商店页面吗?进入网站时出现的第一页。 我使用的主题是 StoreFront。 你能展示你正在使用的钩子吗?还是代码?看。这是我使用的完整代码。

        add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_product_loop_tags', 15 );
        function woocommerce_product_loop_tags() {
            global $post, $product;
    
            $tag_count = sizeof( get_the_terms( $post->ID, 'product_tag' ) );
            $idProducto=$product->id;
             $product->get_title();
            echo $product->get_tags( ', ', '<span class="tagged">' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.</span>' );
    
            $terms = get_terms( 'product_tag' );
            $term_array = array();
            if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                    foreach ( $terms as $term ) {
                        echo " ".$term_array[] = $term->name;
                 }
            }
    }
    

    【讨论】:

    • 我尝试了function.php中的代码,但没有成功:(
    • 我需要 function.php 中的代码作为 get_all_product_tags(){} 函数,然后在主页中调用它。但它没有用。
    猜你喜欢
    • 2016-11-19
    • 2019-11-07
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2017-02-21
    • 2018-07-18
    • 2019-03-08
    相关资源
    最近更新 更多