首先,我是一名初學者,也是PHP的新手,請原諒我的無知。我今天在stackoverflow上問了我的第一個問題,有人提供了一個很好的解決方案,所以我再次嘗試。如何使用wc_customer_bought_product函數來檢查客戶是否在數組中購買產品
我想使用一個函數來檢查客戶是否在登錄時在他的帳戶頁面中購買了產品ID數組內的產品如果他從數組A或產品購買產品,需要顯示不同的菜單數組B,數組C,你得到它。我想爲每個產品id的數組創建一個不同的函數,並將它與一個不同的簡碼相關聯。
我發現在woocommerce功能參考wc_customer_bought_product_function,它是這樣寫的:
/**
* Checks if a user (by email) has bought an item
*
* @access public
* @param string $customer_email
* @param int $user_id
* @param int $product_id
* @return bool
*/
function wc_customer_bought_product($customer_email, $user_id, $product_id) {
global $wpdb;
$emails = array();
if ($user_id) {
$user = get_user_by('id', $user_id);
$emails[] = $user->user_email;
}
if (is_email($customer_email)) {
$emails[] = $customer_email;
}
if (sizeof($emails) == 0) {
return false;
}
return $wpdb->get_var(
$wpdb->prepare("
FROM {$wpdb->prefix}woocommerce_order_items as order_items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON order_items.order_item_id
= itemmeta.order_item_id
LEFT JOIN {$wpdb->postmeta} AS postmeta ON order_items.order_id = postmeta.post_id
LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
WHERE
posts.post_status IN ('wc-completed', 'wc-processing') AND
itemmeta.meta_value = %s AND
itemmeta.meta_key IN ('_variation_id', '_product_id') AND
postmeta.meta_key IN ('_billing_email', '_customer_user') AND
(
postmeta.meta_value IN ('" . implode("','", array_unique($emails)) . "') OR
(
postmeta.meta_value = %s AND
postmeta.meta_value > 0
)
)
", $product_id, $user_id
)
);
}
於是,我就用它來實現通過將剛剛過去的參數是什麼,我想:
// Create function to check if client bought a product from array A
function check_is_category_A_customer()
{
global $woocommerce;
$user_id = get_current_user_id();
$customer_email = $current_user->email;
if (wc_customer_bought_product($customer_email, $user_id, $product_id=array ('2258', '2253',
'2242')))
return true;
return false;
}
// Create shortcode to display menu for customers cat A
add_shortcode('CATA','check_cat_bought_A');
function check_cat_bought_A($atts,$content=""){
if(check_is_category_A_customer()){
return do_shortcode($content);
}
}
但它沒有奏效。當我使用簡碼時,菜單不再出現,但是一旦我購買了一個id在數組中的產品,它就不會顯示。
我嘗試這個版本的基礎上另一個例子的功能:
function check_is_category_A_customer()
{
global $woocommerce;
$user_id = get_current_user_id();
$customer_email = $current_user->email;
if ('' !=wc_customer_bought_product($customer_email, $user_id, $product_id=array ('2258',
'2253', '2242'), true))
return true;
return false;
}
但是,這也不能工作。簡碼不再有效,菜單出現在所有情況下。
我寫了這個使用不同的函數,我作爲模型和信息我偶然發現,我可能犯了可怕的錯誤,因爲它不工作。如果有人知道我做錯了什麼或者如何實現這個目標,那將是一個巨大的幫助!謝謝。
btw:你應該接受前面問題的答案(點擊打勾符號) – David 2014-12-05 01:14:42
完成 - 我希望我可以在這個問題上做同樣的事情;) – Marie 2014-12-05 01:44:53