所以,我一直试图完成与[products limit =“10”columns =“4”best_selling =“true”]短代码完全相同的事情。
我需要将它实现为一个php页面模板,但我已经读过……
total_sales 可以在查询中使用设置 meta_key 。
total_sales
meta_key
从查询返回结果后,只需循环遍历它们并输出所需的任何属性。
$args = array( 'limit' => '10', 'orderby' => array( 'meta_value_num' => 'DESC', 'title' => 'ASC' ), 'meta_key' => 'total_sales', ); $query = new WC_Product_Query( $args ); $products = $query->get_products(); if ( $products ) { foreach ( $products as $product ) { echo $product->get_name(); // Here, we're just listing each product's name } } else { echo __( 'No products found' ); }
的 更新 强>
有了这个更新,我们现在使用的结果 wc_get_products() 在...上 自定义页面模板 改编自 archive-product.php 。这里的目标是避免使用WP_Query / get_posts() 不推荐用于产品查询 。
wc_get_products()
archive-product.php
wc_get_products和WC_Product_Query提供了一种检索产品的标准方法,这些产品可以安全使用,并且不会因未来WooCommerce版本中的数据库更改而中断。构建自定义WP_Queries或数据库查询可能会在未来版本的WooCommerce中破坏您的代码,因为数据会转向自定义表以获得更好的性能。这是插件和主题开发人员检索多个产品的最佳实践方式。 wc_get_products和WC_Product_Query类似于WordPress get_posts和WP_Query。就像那些,你传入一组定义搜索条件的参数。
我们现在能够获得与普通产品类别/存档页面相同的布局/样式,但是我们的顶级卖家查询。我们有产品标题,图片,价格和添加到购物车按钮以及所有应用的WooCommerce /主题样式,而无需像以前的方法那样从头开始构建所有内容(上图)。
在WooCommerce 3.5.6中测试和工作
defined( 'ABSPATH' ) || exit; get_header( 'shop' ); do_action( 'woocommerce_before_main_content' ); ?> <header class="woocommerce-products-header"> <?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?> <h1 class="woocommerce-products-header__title page-title"><?php echo get_the_title(); ?></h1> <?php endif; ?> </header> <?php if ( ! function_exists( 'wc_get_products' ) ) { return; } echo '<div class="woocommerce">'; // needed for default styles $top_selling_products = wc_get_products( array( 'meta_key' => 'total_sales', // our custom query meta_key 'return' => 'ids', // needed to pass to $post_object 'orderby' => array( 'meta_value_num' => 'DESC', 'title' => 'ASC' ), // order from highest to lowest of top sellers ) ); if ( $top_selling_products ) { do_action( 'woocommerce_before_shop_loop' ); woocommerce_product_loop_start(); foreach ( $top_selling_products as $top_selling_product ) { $post_object = get_post( $top_selling_product ); setup_postdata( $GLOBALS['post'] =& $post_object ); do_action( 'woocommerce_shop_loop' ); 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' ); } echo '</div><!-- .woocommerce -->'; do_action( 'woocommerce_after_main_content' ); do_action( 'woocommerce_sidebar' ); get_footer( 'shop' );