當用户登錄時,您可能想要顯示他購買的產品列表,例如在自定義的 「我的帳户」 標籤中。
客户端需要這個,所以我決定把它編碼為一個短碼。請享用!
PHP 代碼段:顯示用户購買的所有產品 – WooCommerce
/** * @snippet Display All Products Purchased by User - WooCommerce * @sourcecode https://businessbloomer.com/?p=22004 * @author Rodolfo Melogli * @compatible Woo 3.0.4 */ add_shortcode( 'my_products', 'bbloomer_user_products_bought' ); function bbloomer_user_products_bought() { global $product, $woocommerce, $woocommerce_loop; $columns = 3; $current_user = wp_get_current_user(); $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => '_visibility', 'value' => array('catalog', 'visible'), 'compare' => 'IN' ) ) ); $loop = new WP_Query($args); ob_start(); woocommerce_product_loop_start(); while ( $loop->have_posts() ) : $loop->the_post(); $theid = get_the_ID(); if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $theid ) ) { wc_get_template_part( 'content', 'product' ); } endwhile; woocommerce_product_loop_end(); woocommerce_reset_loop(); wp_reset_postdata(); return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>'; }
然後使用您需要的簡碼 (僅當用户登錄時才會工作,例如 「我的帳户」 頁面將是理想的):
[my_products]
如何添加此代碼?
1 、您可以將 PHP 代碼片段放置在主題或子主題的 functions.php 文件的底部 (如果是 CSS 代碼,請添加到子主題的 style.css 文件底部) 修改之前建議先備份原始文件,若出現錯誤請先刪除此代碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 代碼也可打開網站前台編輯器的 【自定義】,複製代碼添加到自定義 css 中。
此代碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 用户也希望您的參與。