首页 文章

使用正在销售的产品创建WooCommerce页面

提问于
浏览
0

我正在尝试制作一个页面(默认的woocommerce存档样式),它只显示Sale中的产品 . 这里要提一下,我只有可变产品并不简单 .

我试着制作自定义短代码

global $woocommerce_loop;
    $atts = shortcode_atts( array(
        'per_page' => '-1',
        'columns'  => '4',
        'orderby'  => 'title',
        'order'    => 'asc'
    ), $atts );

    // Get products on sale
    $product_ids_on_sale = wc_get_product_ids_on_sale();

    $meta_query = WC()->query->get_meta_query();
    $args = array(
        'posts_per_page'    => $atts['per_page'],
        'orderby'           => $atts['orderby'],
        'order'             => $atts['order'],
        'no_found_rows'     => 1,
        'post_status'       => 'publish',
        'post_type'         => 'product',
        'meta_query'        => $meta_query,
        'post__in'          => array_merge( array( 0 ), $product_ids_on_sale )
    );
    ob_start();
    $products = new WP_Query( apply_filters( 'woocommerce_shortcode_products_query', $args, $atts ) );
    $columns = absint( $atts['columns'] );
    $woocommerce_loop['columns'] = $columns;
    if ( $products->have_posts() ) : 

        woocommerce_product_loop_start();

            while ( $products->have_posts() ) : $products->the_post(); 

                wc_get_template_part( 'content', 'product' ); 

            endwhile; // end of the loop. 

         woocommerce_product_loop_end(); 

     endif;
    wp_reset_postdata();
    return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';

但结果我只得到2个产品 .

任何帮助或想法?

2 回答

  • 1

    你为什么要创建一个新的短代码? Woocommerce提供了自己的短代码,以自己的档案风格展示销售的产品:

    [sale_products per_page="12"]

    你可以看到整个列表here

  • 1

    我通过创建自定义短代码找到了一个临时解决方案 . 我不知道为什么我没有使用默认的woocommerce短代码获得所有销售产品 .

    这对我有用:

    function variable_sale_products($ atts){global $ woocommerce,$ product;

    $args = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => -1
        );
    
        ob_start();
        $loop = new WP_Query( $args );
    
        if ( $loop->have_posts() ) {
            woocommerce_product_loop_start();
    
            while ( $loop->have_posts() ) : $loop->the_post();
                $id = get_the_ID();
                $_product = wc_get_product( $id );
    
                if($_product->is_on_sale()){    
                    wc_get_template_part( 'content', 'product' );
                }
            endwhile;
    
            woocommerce_product_loop_end(); 
        }
        wp_reset_postdata();
        return '<div class="woocommerce columns-4">' . ob_get_clean() . '</div>';
    }
    add_shortcode( 'variation_sale_product', 'variable_sale_products' );
    

    如果您有任何其他建议,我想听听您的意见

相关问题