【问题标题】:WooCommerce Product Category Image & Category Title On Homepage主页上的 WooCommerce 产品类别图像和类别标题
【发布时间】:2021-12-27 23:07:56
【问题描述】:

我需要显示最新的 8 个;

  • WooCommerce 类别图片
    &
  • WooCommerce 类别标题 在我的主页上。

我已经很容易在标题和href 链接中找到了。 但我也不知道如何获取关联的图像,以创建类别图块。

// Arguments
$args = array(
    'taxonomy' => 'product_cat',
    'posts_per_page' => 8,
    'category_name' => $category->name,
    'orderby' => 'date',
    'order' => 'date' 
);
$categories = get_categories( $args );
foreach( $categories as $category ) { ?>
<a href="<?php echo site_url(product-category) ?><?php echo $category->slug; ?>/">
    <div class="category-tile-image">
        <!-- I NEED THIS -->
        <!-- I NEED THIS -->
        <!-- I NEED THIS -->
        <img src="#">
        <!-- I NEED THIS -->
        <!-- I NEED THIS -->
        <!-- I NEED THIS -->
    </div>
    <h2><?php echo $category->name; ?></h2>
</a>
<?php } ?> 

这是我想要展示的图片。

【问题讨论】:

标签: php wordpress woocommerce custom-wordpress-pages woocommerce-theming


【解决方案1】:

您需要在foreach 循环中添加三样东西才能输出每个类别图像。首先,您需要id of the category,根据它您将获得id of the image,然后根据该ID,您将能够获得image url。因此,在您的 foreach 循环中,您可以执行以下操作:

$image_id = get_term_meta($category->term_id, 'thumbnail_id', true);

$image_url = wp_get_attachment_image_url($image_id, 'thumbnail'); ?>

<img src="<?php echo $image_url; ?>">

所以你的整个代码应该是这样的:

$args = array(
            'taxonomy' => 'product_cat',
            'posts_per_page' => 8,
            'category_name' => $category->name,
            'orderby' => 'date',
            'order' => 'date'
        );
        $categories = get_categories($args);
        foreach($categories as $category) {
            $image_id = get_term_meta($category->term_id, 'thumbnail_id', true);
            $image_url = wp_get_attachment_image_url($image_id, 'thumbnail');
    ?>
            <a href="<?php echo $category->slug; ?>/">
                <div class="category-tile-image">

                    <img src="<?php echo $image_url; ?>">

                </div>
                <h2><?php echo $category->name; ?></h2>
            </a>
<?php }

结果如下:

您可以看到那些有缩略图的类别的图像,而那些没有缩略图的则不会显示任何内容!

【讨论】:

    猜你喜欢
    • 2012-10-21
    • 2018-06-14
    • 2021-01-04
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多