I have just installed woocommerce on this website, I wanted to add a custom field in the edit product page, that seems to be a custom post type (post-type= product), what is wrong in my code? https://pastebin.com/hwgFnXmK
The page I need help with: [log in to see the link]
Since your question involves custom code changes, it’s outside the scope of our support. That said, you’re welcome to join the WooCommerce Community Slack, where developers and contributors might be able to help: https://woocommerce.com/community-slack/
There are different types of fields you can add for use with different product types and you can display your custom field content using different single product page hook locations.
This code adds a text field to simple products.
Use the code in your child themes functions file or code snippets plugin.
// Add custom text field to backend (simple products only) add_action( 'woocommerce_product_options_general_product_data', 'bd_add_custom_backend_text_field' ); function bd_add_custom_backend_text_field() { global $product_object;
if ( $product_object && $product_object->is_type( 'simple' ) ) { echo '<div class="options_group">'; woocommerce_wp_text_input( [ 'id' => '_bd_custom_text', 'label' => __( 'Custom Text Field', 'woocommerce' ), 'desc_tip' => true, 'description' => __( 'Enter a custom value for this simple product.', 'woocommerce' ), ] ); echo '</div>'; } }
// Save the custom field value add_action( 'woocommerce_admin_process_product_object', 'bd_save_custom_backend_text_field' ); function bd_save_custom_backend_text_field( $product ) { if ( isset( $_POST['_bd_custom_text'] ) ) { $product->update_meta_data( '_bd_custom_text', sanitize_text_field( $_POST['_bd_custom_text'] ) ); } }
// Output custom fields on the frontend product page add_action( 'woocommerce_single_product_summary', 'bd_output_custom_product_fields' ); function bd_output_custom_product_fields() {
global $product;
// Only for simple products if ( ! $product->is_type( 'simple' ) ) return;
// Get field values $text = get_post_meta( $product->get_id(), '_bd_custom_text', true );