WooCommerce简码产品列表 [英] WooCommerce shortcode products list
问题描述
我必须制作一个Wordpress插件,该插件添加WooCommerce的简码.我想从特定的产品类别中获取产品,并显示最大数量的产品.简码参数应为类别ID和产品限制.我认为我必须使用WP_Query
对象.
I have to make a Wordpress plugin which adds shortcode for WooCommerce. I want to get products from a specific product category and the maximum number of products to show. The shortcode parameters should be category ID and product limit. I think I should have to use WP_Query
object.
我需要使它看起来像这样:
I need to get it look like this:
短代码如下:[productslist_category="[category_ID]" limit="[product_limit]"]
我使用了下面的代码 LoicTheAztec ):
I used the code below from this answer (thanks to LoicTheAztec):
if( !function_exists('products_list_in_a_product_category') ) {
function products_list_in_a_product_category( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts(
array(
'cat' => '',
'limit' => '4', // default product per page
'column' => '4', // default columns
),
$atts, 'productslist'
);
// The query
$posts = get_posts( array(
'post_type' => 'product',
'posts_per_page' => intval($atts['limit'])+1,
'product_cat' => $atts['cat'],
) );
$output = '<div class="products-in-'.$atts['cat'].'">';
// The loop
foreach($posts as $post_obj)
$ids_array[] = $post_obj->ID;
$ids = implode( ',', $ids_array );
$columns = $atts['column'];
$output .= do_shortcode ( "[products ids=$ids columns=$columns ]" ) . '</div>';
return $output;
}
add_shortcode( 'productslist', 'products_list_in_a_product_category' );}
但是我得到一个错误.内爆功能出现问题.
But I get an error. It says that there is something wrong with the implode function.
推荐答案
这是我原来的答案,是您删除的上一个问题的缩写,您在此处使用的是: 该代码在woocommerce 2.6.x和3+版本中均可完美运行.
这是您(在删除上一个问题之前)采用的原始答案代码:
这是一个基于您的简码与现有的
[product]
WooCommerce简码混合的解决方案.如您所见,您将得到您所期望的……Here is a solution based on your shortcode mixed with existing
[product]
WooCommerce shortcode. As you will see you will get what you are expecting…这是代码:
if( !function_exists('products_list_in_a_product_category') ) { function products_list_in_a_product_category( $atts ) { // Shortcode Attributes $atts = shortcode_atts( array( 'cat' => '', 'limit' => '5', // default product per page 'column' => '4', // default columns ), $atts, 'productslist' ); // The query $posts = get_posts( array( 'post_type' => 'product', 'posts_per_page' => intval($atts['limit'])+1, 'product_cat' => $atts['cat'], ) ); $output = '<div class="products-in-'.$atts['cat'].'">'; // The loop foreach($posts as $post_obj) $ids_array[] = $post_obj->ID; $ids = implode( ',', $ids_array ); $columns = $atts['column']; $output .= do_shortcode ( "[products ids=$ids columns=$columns ]" ) . '</div>'; return $output; } add_shortcode( 'productslist', 'products_list_in_a_product_category' ); }
代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.
此代码已在WooCommerce 3+上经过测试,并且可以正常工作.
This code is tested on WooCommerce 3+ and works.
用法 (示例):
[productslist cat="clothing" limit="4"]
您会得到这个:
-
这篇关于WooCommerce简码产品列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!