我正在尝试创建自定义的Woocommerce产品简码,当将简码添加到页面时,允许我抵消一定数量的产品。通过查看WooCommerce - Recent Products Offset和https://ericwijaya.com/load-woocommerce-loop-custom-arguments/
,我已经能够使偏移部分起作用我遇到的问题是Woocommerce产品的“类别”属性不适用于我的新短代码。我的shorcode看起来像这样:[products_offset limit =“ 8” category =“ fiction” offset =“ 10” orderby =“ menu_order”]
与其显示使用指定类别的子弹(在此情况下为“小说”)的产品,不如显示所有类别的所有产品。
这是我添加到function.php中的代码:
function products_offset_func( $atts ) {
$atts = shortcode_atts( array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'date',
'order' => 'desc',
'offset' => 0,
'category' => '', // Slugs
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
), (array) $atts );
ob_start();
$query_args = array(
'columns' => $atts['columns'],
'posts_per_page' => $atts['per_page'],
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'offset' => $atts['offset'],
'no_found_rows' => 1,
'post_status' => 'publish',
'post_type' => 'product',
'meta_query' => WC()->query->get_meta_query(),
);
?>
<ul class="products">
<?php
$loop = new WP_Query( $query_args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->
<?php
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}
add_shortcode( 'products_offset', 'products_offset_func' );`
任何帮助将不胜感激!
答案 0 :(得分:0)
弄清楚了。我没有将类别标签传递给WP_Query。新增:
if( ! empty( $atts['category'] ) ) {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => trim( $atts['category'] ),
'operator' => $atts['operator']
),
);
}
所以所有代码看起来像这样:
//Shortcode for Offset Products
function products_offset_func( $atts ) {
$atts = shortcode_atts( array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'date',
'order' => 'desc',
'offset' => 0,
'category' => '', // Slugs
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
), (array) $atts );
ob_start();
$query_args = array(
'columns' => $atts['columns'],
'posts_per_page' => $atts['per_page'],
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'offset' => $atts['offset'],
'no_found_rows' => 1,
'post_status' => 'publish',
'post_type' => 'product',
'meta_query' => WC()->query->get_meta_query(),
);
if( ! empty( $atts['category'] ) ) {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => trim( $atts['category'] ),
'operator' => $atts['operator']
),
);
}
?>
<ul class="products">
<?php
$loop = new WP_Query( $query_args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->
<?php
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}
add_shortcode( 'products_offset', 'products_offset_func' );