我编写了一个 WooCommerce 函数,但无法正常工作。
这是代码:
add_filter( 'the_posts', 'move_zero_price_products_to_end', 20, 2 );
function move_zero_price_products_to_end( $posts, $query ) {
if ( ! is_admin() && ( is_shop() || is_product_category() ) ) {
$posts_with_price = array();
$posts_without_price = array();
foreach ( $posts as $post ) {
$price = (float) get_post_meta( $post->ID, '_price', true );
if ( $price <= 0 ) {
$posts_without_price[] = $post;
} else {
$posts_with_price[] = $post;
}
}
$posts = array_merge( $posts_with_price, $posts_without_price );
}
return $posts;
}
但如果我有太多产品,例如我的商店中有 9 页的类别,则无法正常工作
此时,在每个页面中,同一页面的商品中,有价格的商品先显示,无价格或零价格的商品显示在最后。
但一般来说,我想先对所有有价格的产品进行排序,然后将没有价格的产品(它们没有价格 - 它们的价格为零)显示在有价格的产品之后。
您能为我编辑和改进这段代码并解决我的问题吗?
add_filter('woocommerce_get_catalog_ordering_args', 'lowprice_woocommerce_catalog_orderby');
function lowprice_woocommerce_catalog_orderby($args) {
if (is_shop() || is_product_category()) {
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
$args['meta_key'] = '_price';
}
return $args;
}
class iWC_Orderby_Stock_Status {
public function __construct() {
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
add_filter('posts_clauses', array($this, 'order_by_stock_status'), 2000);
}
}
public function order_by_stock_status($posts_clauses) {
global $wpdb;
if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag())) {
$posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
$posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
$posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
}
return $posts_clauses;
}
}
new iWC_Orderby_Stock_Status;