如何在WooCommerce产品页面上创建自定义文本框?

时间:2017-05-04 00:28:44

标签: php wordpress woocommerce

我正在使用WooCommerce功能的WordPress网站上工作。

我使用以下代码为产品页面后端的“产品数据”框创建了2个自定义字段:

<?php
function theme_name_woocommerce_custom_fields() {
    // Price Per Character
    woocommerce_wp_text_input( 
        array(
            'id'          => '_character_price',
            'label'       => 'Price Per Character',
            'description' => 'This is the amount a customer pays per letter entered.',
            'desc_tip'    => 'true',
            'placeholder' => 'Enter Amount per Letter (Exclude the £)'
        ) 
    );
    // Custom Text Box
    woocommerce_wp_checkbox(
        array(
            'id'          => '_custom_text_box',
            'label'       => 'Show Custom Text Box',
            'description' => 'Select this box, if you would like a Custom Text Box to appear on the Product's page.',
            'desc_tip'    => 'true',
        ) 
    );
}
add_action( 'woocommerce_product_options_general_product_data', 'theme_name_woocommerce_custom_fields' );

function save_theme_name_woocommerce_custom_field( $post_id ) {
    if ( ! empty( $_POST['_custom_text_field'] ) ) {
        update_post_meta( $post_id, '_custom_text_field', esc_attr( $_POST['_custom_text_field'] ) );
    }
}
add_action( 'woocommerce_process_product_meta', 'save_theme_name_woocommerce_custom_fields' );
?>

在参考woocommerce_wp_checkbox时,我想创建一个函数,当选中此复选框时,它会在关联的产品页面上创建自定义文本框。然后,潜在客户可以使用此自定义文本框输入他们希望打印到页面产品的文本。

为了达到上述目标,是否有人知道我需要输入哪些额外的编码?

1 个答案:

答案 0 :(得分:1)

您可以覆盖简单/变量产品的模板文件,并在那里添加自定义字段。选中复选框后,保持显示/隐藏文本框的逻辑。

完成添加到购物车后,您将在POST中获取所有发布的数据。从那里抓住并放入woocommerce的对象。

=============================================== ======== 编辑:

您可以按照以下步骤操作:

  1. 将此模板的woocommerce / templates / single-product / add-to-cart / variable.php复制到您的子主题并进行自定义。你会在那里看到一个表单标签。在那里你可以把你的自定义创建复选框(你从管理员添加)。此外,添加自定义文本框(用户将在其中输入文本) - 并隐藏它。

  2. 从functions.php添加自定义js。 - 在这个js中你可以编写逻辑,如果选中复选框,那么你将显示文本框,否则不会。

  3. 现在,当用户确实添加到购物车时,将此自定义文本框数据添加到woocommerce对象。如何向woocommerce对象输入自定义数据 - 您可以在此处获得一步一步的详细信息:https://wisdmlabs.com/blog/add-custom-data-woocommerce-order/