如果您使用WP_Query
然后根据the WooCommerce wiki:
构建自定义WP\\U查询或数据库查询可能会破坏WooCommerce未来版本中的代码,因为数据会向自定义表移动以获得更好的性能。
创建自定义循环的最佳方法是使用wc_get_products()
或WC_Product_Query
.
在你的情况下,我会这样做:
$paged = (get_query_var(\'paged\')) ? absint(get_query_var(\'paged\')) : 1;
$ordering = WC()->query->get_catalog_ordering_args();
$ordering[\'orderby\'] = array_shift(explode(\' \', $ordering[\'orderby\']));
$ordering[\'orderby\'] = stristr($ordering[\'orderby\'], \'price\') ? \'meta_value_num\' : $ordering[\'orderby\'];
$products_per_page = 5;// default is apply_filters(\'loop_shop_per_page\', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page());
$category_products = wc_get_products(array(
\'status\' => \'publish\',
\'limit\' => $products_per_page,
\'page\' => $paged,
\'paginate\' => true,
\'return\' => \'ids\',
\'orderby\' => $ordering[\'orderby\'],
\'order\' => $ordering[\'order\'],
\'category\' => array(\'cap\')
));
wc_set_loop_prop(\'current_page\', $paged);
wc_set_loop_prop(\'is_paginated\', wc_string_to_bool(true));
wc_set_loop_prop(\'page_template\', get_page_template_slug());
wc_set_loop_prop(\'per_page\', $products_per_page);
wc_set_loop_prop(\'total\', $category_products->total);
wc_set_loop_prop(\'total_pages\', $category_products->max_num_pages);
if($category_products) {
do_action(\'woocommerce_before_shop_loop\');
woocommerce_product_loop_start();
foreach($category_products->products as $featured_product) {
$post_object = get_post($featured_product);
setup_postdata($GLOBALS[\'post\'] =& $post_object);
wc_get_template_part(\'content\', \'product\');
}
wp_reset_postdata();
woocommerce_product_loop_end();
do_action(\'woocommerce_after_shop_loop\');
} else {
do_action(\'woocommerce_no_products_found\');
}
事实上,我写了一篇关于这一点的帖子,如果你好奇或想进一步扩展这一点,我会在这里提供更多细节:
https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/