【问题标题】:I want to display random Product Image of distinct product_cat in Woocommerce我想在 Woocommerce 中显示不同 product_cat 的随机产品图像
【发布时间】:2018-01-26 03:58:22
【问题描述】:

我正在尝试显示不同产品类别的随机产品图片。将它们链接到类别页面并获取类别标题。我的代码得到了随机图像,但是太多了,不知道如何获取类别 slug 和标题。

$args = array(
        'taxonomy'     => 'product_cat',
        'posts_per_page' => -1,
        'showposts' => -1, 
        'numberposts'     => -1,
        'orderby' => 'rand',
);

$the_query = new WP_Query( $args );

while ($the_query->have_posts()) : $the_query->the_post();
    $temp_thumb = get_the_post_thumbnail($post->ID, 'shop_thumbnail', array('class' => 'attachment-shop_catalog size-shop_catalog wp-post-image'));
    $temp = get_term($post->ID, 'product_cat');
    $temp_title = $temp->name;
    $temp_url = $temp->slug;
    echo '<a href="' . $temp_url . '">' . $temp_thumb . $temp_title . '</a>';
endwhile;

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    如果我正确理解您的问题,您正在尝试创建产品类别列表,该列表链接到每个单独类别的产品存档页面,并且您希望这些类别列表项中的每一个都包含从以下选项中选择的图像下一个随机产品?

    如果是这种情况,在创建新的 WP_Query 对象之前,您可能会是一个更好的服务器,从 get_terms() 查询开始。

    流程如下:

    1. 遍历所有产品类别
    2. 为每个类别创建一个列表项
    3. 快速查询随机产品并提取其特色图片。

    类似这样的:

    //get terms (i.e. get all product categories)
    $arguments = array(
        'taxonomy' => 'product_cat',
        'hide_empty' => false,
        );
    $terms = get_terms( $arguments );
    
    //loop through each term
    foreach ($terms as $term) {
        echo $term->name;
        echo '<br>';
        echo get_random_featured_image($term->term_id);
        echo '<br>';
    }
    
    //function to get random product based on product category id
    function get_random_featured_image($term_id) {
        $arguments = array(
            'post_type' => 'product',
            'orderby' => 'rand', //this grabs a random post
            'posts_per_page' => 1,
            'tax_query' => array(
                    array(
                        'taxonomy' => 'product_cat',
                        'field'    => 'term_id',
                        'terms'    => $term_id, //this makes sure it only grabs a post from the correct category
                    ),
                ),
            );
        $query = new WP_Query($arguments);
        while($query->have_posts()) {
            $query->the_post();
            $image_src = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium' )[0];
        }
        wp_reset_postdata();
        return $image_src; //return the image url
    }
    

    【讨论】:

    • 谢谢,这正是我需要的。我试图实现代码,但它返回 Array 而不是 image_src。
    • 啊!我很抱歉,wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium' ) 应该得到一个 [0] 后面,我已经编辑了代码 - 以反映这一点:)
    • 很高兴听到:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多