【问题标题】:How to limit returned product categories with thumbnails (WooCommerce)如何使用缩略图限制返回的产品类别(WooCommerce)
【发布时间】:2020-05-21 15:57:06
【问题描述】:

我的目标是仅显示类别 ID 93(供应商)下的子类别以及缩略图和 URL,以便人们可以单击供应商徽标并查看该类别中的其他产品。我的一切大部分都在工作,但我不确定如何限制我的请求,只显示我父母的一个孩子。诚然,这很业余——我不是后端开发人员,也不太了解如何编写 PHP。

<?php
echo $wp_query;

$terms_post = get_the_terms($product->ID, 'product_cat');

foreach ($terms_post as $term_cat) { 
    $term_cat_id = $term_cat->term_id;
    $category_url = get_term_link( $term_cat_id, 'product_cat', true );
    $thumbnail_id = get_woocommerce_term_meta($term_cat_id, 'thumbnail_id', true );
    $image_url = wp_get_attachment_url( $thumbnail_id );
    echo '<a href="'. $category_url .'"><img src="' . $image_url . '" alt="" width="50" height="50"></a>'; 
} 
?>

【问题讨论】:

    标签: php wordpress woocommerce categories


    【解决方案1】:

    要仅显示父级中的 1 个子级,只需使用 array_slice()。

    foreach(array_slice($terms_post, 0, 1) as $term_cat ) { 
        $term_cat_id = $term_cat->term_id;
        $category_url = get_term_link( $term_cat_id, 'product_cat', true );
        $thumbnail_id = get_woocommerce_term_meta($term_cat_id, 'thumbnail_id', true );
        $image_url = wp_get_attachment_url( $thumbnail_id );
        echo '<a href="'. $category_url .'"><img src="' . $image_url . '" alt="" width="50" height="50"></a>'; 
    } 
    

    如果它有效,请告诉我。

    已编辑:

    使用以下代码使用父类别 slug 获取子类别。

    <?php
    global $post;
    $category_id = get_term_by('slug', 'PARENT-CAT-SLUG', 'product_cat');
    
    $terms = get_the_terms($post->ID, 'product_cat');
    foreach ($terms as $term) {
        if($term->parent === $category_id->term_id) { ?>
           <span class="product-sub-cats"><?php echo $term->name; ?></span>
          <?php  break;
        }
    }
     ?>
    

    将“PARENT-CAT-SLUG”替换为您的父类别的 slug。

    【讨论】:

    • 拉吉夫,这太棒了。它几乎可以完成这项工作,但我只想显示类别 93(供应商)的子类别。它只会显示 1 个缩略图,因为只应用了一个品牌 - 所以如果我的产品是 Widget Maker 的小部件,我想在元数据的其余部分下方显示他们的徽标。这更有意义吗?
    • 这是完美的工作,我只需要添加缩略图和链接回来。我想我可以做到,但我们会看到:) ID, 'product_cat'); foreach ($terms as $term) { if($term->parent === $category_id->term_id) { ?> name; ?>
    • 很高兴能帮到你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2016-08-23
    • 2021-07-02
    • 2021-04-12
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多