Woocommerce产品类型短代码

时间:2016-04-17 06:24:58

标签: wordpress woocommerce shortcode product

在woocommerce短代码中按类型过滤产品的语法是什么?我尝试了以下尝试失败。

[products product_type="simple" per_page="12" columns="3"]

[products type="simple" per_page="12" columns="3"]

1 个答案:

答案 0 :(得分:2)

//products by type shortcode
function products_by_type($atts) {
    $atts = shortcode_atts( array(
        'columns' => '4',
        'orderby' => 'title',
        'order'   => 'asc',
        'ids'     => '',
        'skus'    => '',
        'product_type'    => 'simple'
    ), $atts );

    $query_args = array(
        'post_type'           => 'product',
        'post_status'         => 'publish',
        'ignore_sticky_posts' => 1,
        'orderby'             => $atts['orderby'],
        'order'               => $atts['order'],
        'posts_per_page'      => -1,
        'meta_query'          => WC()->query->get_meta_query(),
        'tax_query'           => array(
                                    array(
                                            'taxonomy' => 'product_type',
                                            'field'    => 'slug',
                                            'terms'    => $atts['product_type'],
                                        ),
                                    ),
    );

    if ( ! empty( $atts['skus'] ) ) {
        $query_args['meta_query'][] = array(
            'key'     => '_sku',
            'value'   => array_map( 'trim', explode( ',', $atts['skus'] ) ),
            'compare' => 'IN'
        );
    }

    if ( ! empty( $atts['ids'] ) ) {
        $query_args['post__in'] = array_map( 'trim', explode( ',', $atts['ids'] ) );
    }

    return product_loop( $query_args, $atts, 'products' );
}

function product_loop( $query_args, $atts, $loop_name ) {
    global $woocommerce_loop;

    $products                    = new WP_Query( apply_filters( 'woocommerce_shortcode_products_query', $query_args, $atts, $loop_name ) );
    $columns                     = absint( $atts['columns'] );
    $woocommerce_loop['columns'] = $columns;

    ob_start();

    if ( $products->have_posts() ) {
        do_action( "woocommerce_shortcode_before_{$loop_name}_loop" );
        woocommerce_product_loop_start();
        while ( $products->have_posts() ) {
            $products->the_post();
            wc_get_template_part( 'content', 'product' );
        }

        woocommerce_product_loop_end();
        do_action( "woocommerce_shortcode_after_{$loop_name}_loop" );

    }

    woocommerce_reset_loop();
    wp_reset_postdata();

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

add_shortcode( apply_filters( "products_by_type_shortcode_tag", "products_by_type" ), "products_by_type" );