我正在尝试设置一个用户可以继续浏览的页面,他们可以看到他们以标准Woocommerce格式购买的所有产品,这样他们就可以将更多的产品添加到购物车中.
我试过这个,但每次只有1个出现烦人:
<ul class="products">
[insert_php]
$user_id = get_current_user_id();
$current_user = wp_get_current_user();
$customer_email = $current_user->email;
$args = array(
'post_type' => 'product',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) :
$loop->the_post();
$_product = get_product( $loop->post->ID );
if (wc_customer_bought_product($customer_email, $user_id,$_product->id)){
woocommerce_get_template_part( 'content', 'product' );
}
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
[/insert_php]
</ul><!--/.products-->
最佳答案 您的代码有什么问题,您每页将获得12个产品,但只显示用户购买的产品.因此,如果在该页面中偶然出现,只有一个已购买的产品,则会显示该产品,而不会显示其他产品.如果在该页面中偶然发现没有购买的产品,则不会显示任何内容.试试这个:
<ul class="products">
[insert_php]
global $wpdb;
$current_user = wp_get_current_user();
$customer_email = $current_user->user_email;
$customer_data = array( $customer_email );
$statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
$result = $wpdb->get_col( "
SELECT im.meta_value FROM {$wpdb->posts} AS p
INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items AS i ON p.ID = i.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS im ON i.order_item_id = im.order_item_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $statuses ) . "' )
AND pm.meta_key IN ( '_billing_email', '_customer_user' )
AND im.meta_key IN ( '_product_id', '_variation_id' )
AND im.meta_value != 0
AND pm.meta_value IN ( '" . implode( "','", $customer_data ) . "' )
" );
$product_ids = array_map( 'absint', $result );
if ( !empty( $product_ids ) ) {
$args = array(
'post_type' => 'product',
'post__in' => $product_ids,
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) :
$loop->the_post();
woocommerce_get_template_part( 'content', 'product' );
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
} else {
echo __( 'No products found' );
}
[/insert_php]
</ul><!--/.products-->
sql代码部分取自WooCommerce wc_customer_bought_product
函数.此功能的作用是获取给定电子邮件地址所购买的所有产品,从而将数据生成为一系列产品ID.获得所有产品后,如果在这些产品中,您的产品ID将被测试.所以,是的,减去测试部分,这就是我们所需要的.