【问题标题】:Woocommerce product loop - show all product variation-imagesWoocommerce 产品循环 - 显示所有产品变体图像
【发布时间】:2017-10-26 19:31:58
【问题描述】:

在 wordpress front-page.php 主题文件中,我循环浏览所有 woocommerce 产品并显示特色图片。

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

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

【问题讨论】:

    标签: wordpress loops woocommerce


    【解决方案1】:
    <?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 ?>
    

    我还没有测试过。但希望它会起作用。

    【讨论】:

    • 它有效,我从产品变体中获取所有数据。但是我现在怎么才能输出所有变体的图像路径呢?
    • 在下面添加了答案。请检查。
    • Linter 说“未定义的方法 'get_available_variations' ,没有任何内容被回显。
    【解决方案2】:

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

    对于 Wc3+

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

    对于旧的 Wc 版本

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

    【讨论】:

      【解决方案3】:
       $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>";
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-24
        • 2018-12-19
        • 1970-01-01
        • 2022-06-13
        相关资源
        最近更新 更多