按照产品类别在WooCommerce的简码中获取产品
问题描述:
我有一个简码,我想从特定的Woocommerce类别获得所有产品。按照产品类别在WooCommerce的简码中获取产品
add_shortcode('list-products', 'prod_listing_params');
function prod_listing_params($atts) {
ob_start();
extract(shortcode_atts(array (
'type' => 'product',
'order' => 'date',
'orderby' => 'title',
'posts' => -1,
'category' => '',
), $atts));
$options = array(
'post_type' => $type,
'order' => $order,
'orderby' => $orderby,
'posts_per_page' => $posts,
'product_cat' => $product_cat,
);
$query = new WP_Query($options);
if ($query->have_posts()) { ?>
<div class="#">
<?php while ($query->have_posts()) : $query->the_post(); ?>
<p class="#">
<span id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</span></p>
<?php endwhile;
wp_reset_postdata(); ?>
</div>
<?php
$myvar = ob_get_clean();
return $myvar;
}
}
于是我就用短码:
[list-products category="shoes"]
但是,尽管在短码提供的类别返回全部来自所有类别产品。
我该如何修改这个以获得分类?
感谢
答
而不是'product_cat' => $product_cat,
你应该使用tax_query
这样:
'tax_query' => array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['cat'],
)),
所以,你的代码应该是这样(我已经重新审视了一下你的代码):
// Creating a shortcode that displays a random product image/thumbail
if(!function_exists('prod_listing_params')) {
function prod_listing_params($atts) {
ob_start();
$atts = shortcode_atts(array (
'type' => 'product',
'order' => 'date',
'orderby' => 'title',
'posts' => -1,
'category' => '', // category slug
), $atts, 'list_products');
$query = new WP_Query(array(
'post_type' => $atts['type'],
'order' => $atts['order'],
'orderby' => $atts['orderby'],
'posts_per_page' => $atts['posts'],
'tax_query' => array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
)),
));
if ($query->have_posts()) {
?>
<div class="#">
<?php while ($query->have_posts()) : $query->the_post(); ?>
<p class="#">
<span id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</span></p>
<?php endwhile;
wp_reset_postdata(); ?>
</div>
<?php
$myvar = ob_get_clean();
return $myvar;
}
}
add_shortcode('list_products', 'prod_listing_params');
}
C ode在你的活动子主题(或主题)的function.php文件中,或者也在任何插件文件中。
实例:
[list_products category="shoes"]
相关的答案:
答
您还可以使用WooCommerce自己提供的简码
[product_category category="appliances"]
+0
是的,我遇到的唯一问题是,我的主题开始提供自己的风格,而且我会改变它来显示产品变体,而不用换个新页面。但你的回答站起来欢呼! –
完美!谢谢 –