[英]Woocommerce: Filter admin products by “on sale”
我在下面找到了這段代碼,它在 Woocommerce 管理產品列表上添加了一個不錯的“按銷售過濾”下拉過濾器。
不知何故,此代碼與訂單編輯頁面有沖突。 如果我打開一個編輯訂單會出現錯誤“注意:未定義索引:post_type in /wp-content/plugins/code-snippets/php/snippet-ops.php(469) : eval()'d code on line 36"
第 36 行說: if (!is_admin() || $_GET['post_type'] != "product" || !$selected) {
有沒有辦法修復代碼片段,以免弄亂訂單編輯頁面?
這是我正在使用的完整代碼。
/*
* Woocommerce Filter by on sale
*/
function custom_woocommerce_filter_by_onsale($output) {
global $wp_query;
$selected = filter_input(INPUT_GET, 'product_sale', FILTER_VALIDATE_INT);
if ($selected == false) {
$selected = 0;
}
$output .= '
<select id="dropdown_product_sale" name="product_sale">
<option value="">Filter by sale</option>
<option selected="selected" value="1">On sale</option>
<option selected="selected" value="2">Not on sale</option>
</select>
';
return $output;
}
add_action('woocommerce_product_filters', 'custom_woocommerce_filter_by_onsale');
/*
* Woocommerce Filter by on sale where statement
*/
function custom_woocommerce_filter_by_onsale_where_statement($where) {
global $wp_query, $wpdb;
// Get selected value
$selected = filter_input(INPUT_GET, 'product_sale', FILTER_VALIDATE_INT);
// Only trigger if required
if (!is_admin() || $_GET['post_type'] != "product" || !$selected) {
return $where;
}
$productsIDs = [];
if ($selected == 1) {
$querystr = '
SELECT p.ID, p.post_parent
FROM ' . $wpdb->posts . ' p
WHERE p.ID IN (
SELECT post_id FROM ' . $wpdb->postmeta . ' pm WHERE pm.meta_key = "_sale_price" AND pm.meta_value > \'\'
)
';
$pageposts = $wpdb->get_results($querystr, OBJECT);
$productsIDs = array_map(function($n){
return $n->post_parent > 0 ? $n->post_parent : $n->ID;
}, $pageposts);
} elseif ($selected == 2) {
$querystr = '
SELECT p.ID, p.post_parent
FROM ' . $wpdb->posts . ' p
WHERE p.ID NOT IN (
SELECT post_id FROM ' . $wpdb->postmeta . ' pm WHERE pm.meta_key = "_sale_price" AND pm.meta_value > \'\'
)
';
$pageposts = $wpdb->get_results($querystr, OBJECT);
$productsIDs = array_map(function($n){
return $n->post_parent > 0 ? $n->post_parent : $n->ID;
}, $pageposts);
}
$where .= ' AND ' . $wpdb->posts . '.ID IN (' . implode(",", $productsIDs) . ') ';
return $where;
}
add_filter('posts_where' , 'custom_woocommerce_filter_by_onsale_where_statement');
警告是由於 $GET 並不總是可用的事實。
代替:
if (!is_admin() || $_GET['post_type'] != "product" || !$selected) {
用
if (!is_admin() || !isset($_GET['post_type']) || $_GET['post_type'] != "product" || !$selected) {
或更好
if (!is_admin() || get_query_var('post_type') != "product" || !$selected) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.