當使用者登入時,您可能想要顯示他購買的產品列表,例如在自定義的 「我的帳戶」 標籤中。
客戶端需要這個,所以我決定把它編碼為一個短碼。請享用!
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 使用者也希望您的參與。