我喜歡與自由職業者合作,並與世界各地分享我的片段!
這次,客户要求在單一產品頁面上顯示 「產品查詢」 按鈕,該按鈕將顯示一個具有自動填充主題的聯繫表單 (當然是聯繫表格 7) 。這是我如何做到的!

PHP 片段:將 CF7 添加到單個產品頁面 – WooCommerce
/** * @snippet Show Product Inquiry CF7 @ Single Product Pg - WooCommerce * @sourcecode https://businessbloomer.com/?p=21605 * @author Rodolfo Melogli * @compatible WC 2.6.14, WP 4.7.2, PHP 5.5.9 */ // -------------------------- // 1. Display Button and Echo CF7 add_action( 'woocommerce_single_product_summary', 'bbloomer_woocommerce_cf7_single_product', 30 ); function bbloomer_woocommerce_cf7_single_product() { echo '<button type="submit" id="trigger_cf" class="single_add_to_cart_button button alt">Product Inquiry</button>'; echo '<div id="product_inq" style="display:none">'; echo do_shortcode('[paste_your_contact_form_7_shortcode_here]'); echo '</div>'; } // -------------------------- // 2. Echo Javascript: // a) on click, display CF7 // b) and populate CF7 subject with Product Name // c) and change CF7 button to "Close" add_action( 'woocommerce_single_product_summary', 'bbloomer_on_click_show_cf7_and_populate', 40); function bbloomer_on_click_show_cf7_and_populate() { ?> <script type="text/javascript"> jQuery('#trigger_cf').on('click', function(){ if ( jQuery(this).text() == 'Product Inquiry' ) { jQuery('#product_inq').css("display","block"); jQuery('input[name="your-subject"]').val('<?php the_title(); ?>'); jQuery("#trigger_cf").html('Close'); } else { jQuery('#product_inq').hide(); jQuery("#trigger_cf").html('Product Inquiry'); } }); </script> <?php }
如何添加此代碼?
1 、您可以將 PHP 代碼片段放置在主題或子主題的 functions.php 文件的底部 (如果是 CSS 代碼,請添加到子主題的 style.css 文件底部) 修改之前建議先備份原始文件,若出現錯誤請先刪除此代碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 代碼也可打開網站前台編輯器的 【自定義】,複製代碼添加到自定義 css 中。
此代碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 用户也希望您的參與。