php 我想在Woocommerce中显示不同产品的随机产品图像_cat

iezvtpos  于 2022-11-21  发布在  PHP
关注(0)|答案(1)|浏览(122)

我试图显示不同产品类别的随机产品图像。将它们链接到类别页并获得类别标题。我用我的代码获得随机图像,但太多,不知道如何获得类别鼻涕虫和标题。

$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;
bbmckpt7

bbmckpt71#

如果我没理解错你的问题,你想创建一个产品类别列表,链接到每个类别的产品存档页面,你想让每个类别列表项包含一个从随机产品中选择的图像?
如果是这种情况,在创建新的WP_Query对象之前,从get_terms()查询开始可能会更好。
过程如下:
1.遍历所有产品类别
1.创建每个类别的列表项
1.做一个随机产品的快速查询,并拉它的特色图片。
大概是这样的:

//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
}

相关问题