las*_*oob 5 php wordpress product woocommerce
所以,我一直在尝试做与短代码完全相同的事情[products limit="10" columns="4" best_selling="true" ]
。
我需要将它实现到 php 页面模板,但我读到 do_shortcode 是不好的做法,我想以正确的方式做到这一点。
这是我到目前为止所拥有的,但是我该去哪里呢?
$args = array(
'limit' => '10',
'columns' => '4',
'orderby' => 'total_sales',
'order' => 'DESC',
);
$products = wc_get_products( $args );
Run Code Online (Sandbox Code Playgroud)
如果我理解正确的话,这将保存 10 个最畅销的产品,按 $产品的总销售额递减。这不正确吗?
如何正确显示 $products 中的实际产品列表(就像短代码一样)?
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' );
}
Run Code Online (Sandbox Code Playgroud)
更新
通过此更新,我们现在使用改编自 的自定义页面模板wc_get_products()
上的 结果。这里的目标是避免使用 WP_Query/get_posts(),因为不建议将它们用于产品查询。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' );
Run Code Online (Sandbox Code Playgroud)