Woocommerce产品循环 - 显示所有产品变异图像

时间:2017-10-26 09:53:19

标签: wordpress loops woocommerce

在wordpress front-page.php主题文件中,我遍历所有的woocoommerce产品并显示特色图片。

            <ul class="products">
                <?php

                // Setup your custom query
                $args = array( 'post_type' => 'product' );
                $loop = new WP_Query( $args );

                while ( $loop->have_posts() ) : $loop->the_post(); ?>
                    <li>
                        <a href="<?php echo get_permalink( $loop->post->ID ) ?>">
                            <?php the_post_thumbnail( ); ?>
                        </a>
                    </li>

                <?php endwhile; wp_reset_query(); // Remember to reset ?>
            </ul>

现在我有一些产品是可变产品(不同颜色)。每种颜色变化都有自己的图像。如何在此循环中显示所有不同的变体图像?我的计划是用这些图像创建一个图像滑块。

3 个答案:

答案 0 :(得分:4)

<?php
            $args = array( 'post_type' => 'product' );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
                $product_s = wc_get_product( $loop->post->ID ); 
                if ($product_s->product_type == 'variable') {
                    $args = array(
                    'post_parent' => $plan->ID,
                    'post_type'   => 'product_variation',
                    'numberposts' => -1,
                    );
                    $variations = $product_s->get_available_variations();
                    echo '<pre>';
                    print_r($variations);
                    // You may get all images from $variations variable using loop
                    echo '</pre>';
                }
            endwhile; wp_reset_query(); // Remember to reset ?>

我还没有测试过。但希望它能奏效。

答案 1 :(得分:1)

使用以下代码获取图片网址

对于Wc3 +

foreach ( $variations as $variation ) {
    echo $variation['image']['url'];
}

对于旧的Wc版本

foreach ( $variations as $variation ) {
    echo $variation['image_src'];
}

答案 2 :(得分:1)

 $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
    );
    $product_arrray = get_posts($args);
    foreach($product_arrray as $prod)
    {
        $product_id = $prod->ID;
        $product = wc_get_product($product_id);
        $pvariation = $product->get_available_variations();
        echo "<pre>";print_r($pvariation);echo "</pre>";
    }
相关问题