您所在位置:
WooCommerce: 按销售状态过滤产品 @ WP 控制面板
管理 WooCommerce 商店意味着要密切关注产品定价,尤其是在进行促销或销售时。然而,使用默认的 WordPress 管理界面,在数百甚至数千种产品中进行排序,以找到具有活动促销价格的产品,可能是一项乏味的任务。
试想一下,如果能快速过滤产品列表,只显示当前正在销售的产品,您就可以简化更新和促销策略…
在本篇文章中,我将向您展示如何通过一个简单的 PHP 代码段来增强您的 WooCommerce 管理面板,为销售状态添加一个自定义过滤器。
这个解决方案不仅能节省您的时间,还能简化库存管理,让您更轻松地策划营销活动并有效更新产品详细信息。让我们深入代码,开始使用!

PHP 代码段: 添加 “按销售状态过滤 ”下拉菜单 @ WooCommerce 产品管理员
add_action( 'restrict_manage_posts', 'bbloomer_filter_products_by_sale_status', 9999 );
function bbloomer_filter_products_by_sale_status() {
global $typenow;
if ( 'product' === $typenow ) {
$selected = isset( $_GET['sale_status'] ) ? $_GET['sale_status'] : '';
?>
<select name="sale_status">
<option value="">Filter by sale status</option>
<option value="on_sale" <?php selected( $selected, 'on_sale' ); ?>>On Sale</option>
<option value="not_on_sale" <?php selected( $selected, 'not_on_sale' ); ?>>Not on Sale</option>
</select>
<?php
}
}
add_filter( 'request', 'bbloomer_filter_products_query_by_sale_status' );
function bbloomer_filter_products_query_by_sale_status( $query_vars ) {
if ( isset( $query_vars['post_type'] ) && 'product' === $query_vars['post_type'] && isset( $_GET['sale_status'] ) && '' !== $_GET['sale_status'] ) {
$sale_status = sanitize_text_field( wp_unslash( $_GET['sale_status'] ) );
$now = current_time( 'timestamp' );
if ( ! isset( $query_vars['meta_query'] ) || ! is_array( $query_vars['meta_query'] ) ) {
$query_vars['meta_query'] = array();
}
if ( 'on_sale' === $sale_status ) {
$query_vars['meta_query'][] = array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'NUMERIC',
);
$query_vars['meta_query'][] = array(
'relation' => 'OR',
array(
'key' => '_sale_price_dates_from',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_sale_price_dates_from',
'value' => $now,
'compare' => '<=',
'type' => 'NUMERIC',
),
);
$query_vars['meta_query'][] = array(
'relation' => 'OR',
array(
'key' => '_sale_price_dates_to',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_sale_price_dates_to',
'value' => $now,
'compare' => '>=',
'type' => 'NUMERIC',
),
);
} elseif ( 'not_on_sale' === $sale_status ) {
$query_vars['meta_query'][] = array(
'relation' => 'OR',
array(
'key' => '_sale_price',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_sale_price',
'value' => '',
'compare' => '=',
),
array(
'key' => '_sale_price_dates_from',
'value' => $now,
'compare' => '>',
'type' => 'NUMERIC',
),
array(
'key' => '_sale_price_dates_to',
'value' => $now,
'compare' => '<',
'type' => 'NUMERIC',
),
);
}
}
return $query_vars;
}






