WP SITES

3086 Coded Tutorials & 289 Plugins

Single Product Page Custom Fields for WooCommerce

This PHP codes creates 3 custom fields for single products. This enables you to add unique content for each simple product.

The content outputs on the frontend using the woocommerce_single_product_summary single product page hook.


add_action('woocommerce_product_options_general_product_data', 'add_custom_fields');
function add_custom_fields() {

    woocommerce_wp_text_input( array(
        'id'          => '_shipping_detail',
        'label'       => 'Shipping Detail',
        'desc_tip'    => 'true',
        'description' => 'Enter the shipping details.',
    ));

    woocommerce_wp_text_input( array(
        'id'          => '_manufacture_info',
        'label'       => 'Manufacture Info',
        'desc_tip'    => 'true',
        'description' => 'Enter the manufacture information.',
    ));

    woocommerce_wp_textarea_input( array(
        'id'          => '_product_terms',
        'label'       => 'Terms',
        'desc_tip'    => 'true',
        'description' => 'Enter the terms.',
    ));
}

add_action('woocommerce_admin_process_product_object', 'save_custom_fields');
function save_custom_fields($product) {

    if (isset($_POST['_shipping_detail'])) {
        $product->update_meta_data('_shipping_detail', sanitize_text_field($_POST['_shipping_detail']));
    }
    if (isset($_POST['_manufacture_info'])) {
        $product->update_meta_data('_manufacture_info', sanitize_text_field($_POST['_manufacture_info']));
    }
    if (isset($_POST['_product_terms'])) {
        $product->update_meta_data('_product_terms', sanitize_text_field($_POST['_product_terms']));
    }
}

add_action('woocommerce_single_product_summary', 'display_custom_fields', 25);
function display_custom_fields() {

    global $product;
    
    $shipping_detail = $product->get_meta('_shipping_detail');
    $manufacture_info = $product->get_meta('_manufacture_info');
    $product_terms = $product->get_meta('_product_terms');

    if ($shipping_detail) {
        echo '<p><strong>Shipping Detail:</strong> ' . esc_html($shipping_detail) . '</p>';
    }
    if ($manufacture_info) {
        echo '<p><strong>Manufacture Info:</strong> ' . esc_html($manufacture_info) . '</p>';
    }
    if ($product_terms) {
        echo '<p><strong>Terms:</strong> ' . wp_kses_post($product_terms) . '</p>';
    }
}

Add the code to the end of your child themes functions file using FTP and a code editor.

Leave a Reply

New Plugins