【发布时间】:2015-02-03 02:07:11
【问题描述】:
首先,我是一个初学者和php新手,所以请原谅我的无知。我今天在 stackoverflow 上问了我的第一个问题,有人很好地提供了一个很好的解决方案,所以我再试一次。
我正在尝试使用一个函数来检查客户是否在登录后的帐户页面中购买了产品 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;
}
但这也不起作用。简码不再有效,菜单出现在所有情况下。
我使用不同的函数作为模型和我偶然发现的信息编写了这个,我可能犯了严重的错误,因为它不起作用。如果有人知道我做错了什么或者如何以不同的方式实现这个目标,那将是一个巨大的帮助!谢谢。
【问题讨论】:
-
顺便说一句:你应该接受前面问题的答案(点击勾号)
-
完成 - 我希望我能在这个问题上做同样的事情;)
标签: php wordpress function woocommerce shortcode