我必须制作一个增加短代码的Wordpress插件 . 使用短代码我想获得特定类别的产品和要显示的最大产品数量 . 短代码参数应该是类别ID和产品限制 . 我想我应该使用WP_Query对象 .
我需要看起来像这样:https://prnt.sc/fx5k3u
短代码将是这样的: [productslist_category="[category_ID]" limit="[product_limit]"]
我使用了下面的代码from this answer(感谢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' );}
但是我收到了一个错误 . 它说内爆功能有问题 .
2 回答
The code works perfectly in woocommerce versions 2.6.x and 3+.
That was my original answer code that you have taken (before deleting your previous question):
这是一个基于您的短代码和现有的
[product]
WooCommerce短代码的解决方案 . 正如您将看到的那样,您将得到您所期待的......这是代码:
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中 .
此代码在WooCommerce 3上进行测试并正常运行 .
USAGE (示例):
你会得到这个:
$ args = array('post_type'=>'product','post_status'=>'publish','ignore_sticky_posts'=> 1,'posts_per_page'=>'12','meta_query'=> array(array('key '=>'_visibility','value'=> array('catalog','visible'),'compare'=>'IN')),'tax_query'=> array(array('taxonomy'=>'product_cat ','field'=>'term_id',//这是可选的,因为它默认为'term_id''terms'=> 26,'operator'=>'IN'//可能的值为'IN','NOT IN','AND' . ))); $ products = new WP_Query($ args); var_dump($ products);