我已经向我的帐户添加了一个自定义终结点"推荐图书".使用快捷码,我显示了一个产品列表.我想隐藏用户已经购买的产品.但我所有的try 都没有奏效.
// That's how I added the Recommended books endpoint to my account
add_filter ( 'woocommerce_account_menu_items', 'recommended_books_link', 25 );
function recommended_books_link( $menu_links ){
$menu_links = array_slice( $menu_links, 0, 1, true ) + array( 'recommended-books' => 'Recommended books' ) +
array_slice( $menu_links, 1, NULL, true );
return $menu_links;
}
add_action( 'init', 'you_add_endpoints', 25 );
function you_add_endpoints() {
add_rewrite_endpoint( 'recommended-books', EP_PAGES );
}
add_action( 'woocommerce_account_recommended-books_endpoint', 'you_contents', 25 );
function you_contents() {
echo '<div class="sav" style= "margin-bottom: 25px;" > <h1>Recommended books_link</h1>
</div>';
echo do_shortcode('[products limit="10" columns="1" paginate="true"]');
}
这是我用来隐藏用户购买的产品的代码.但它不起作用...
//Hide product
add_action( 'pre_get_posts', 'hide_product_from_shop_page_if_user_already_purchased', 20);
function hide_product_from_shop_page_if_user_already_purchased( $query ) {
if ( ! $query->is_main_query() ) return;
if ( ! is_admin() && is_page() && is_shop()) {
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) return;
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $current_user->ID,
'post_type' => 'shop_order',
'post_status' => array( 'wc-processing', 'wc-completed' ),
) );
if ( ! $customer_orders ) return;
$product_ids = array();
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order->ID );
if( $order ){
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$product_ids[] = $product_id;
}
}
}
$product_ids = array_unique( $product_ids );
$query->set( 'post__not_in', $product_ids );
}
}