John Davidson

php - How to Add Custom Image Field to WooCommerce Product Creation Panel?

0 comments
Message:


I need to add a field to select/delete a picture for a product. The field must be done by code, without using a plugin. How can i do this?
Now I have added a text field and I am saving it. How to add a custom field for an image?




// Display Fields
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');
// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

function woocommerce_product_custom_fields()
{
global $woocommerce, $post;
echo '<div class="product_custom_field">';
woocommerce_wp_text_input(
array(
'id' => '_custom_product_text_field',
'placeholder' => 'Custom Product Text Field',
'label' => __('Custom Product Text Field', 'woocommerce'),
'desc_tip' => 'true'
)
);
echo '</div>';

}

function woocommerce_product_custom_fields_save($post_id)
{
// Custom Product Text Field
$woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
if (!empty($woocommerce_custom_product_text_field))
update_post_meta($post_id, '_custom_product_text_field', esc_attr($woocommerce_custom_product_text_field));

}


My Answer:
To add a custom image field to the WooCommerce product creation panel, you can use the following code:

php
// Display Fields
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');
// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

function woocommerce_product_custom_fields()
{
global $woocommerce, $post;
echo '
';
woocommerce_wp_text_input(
array(
'id' => '_custom_product_text_field',
'placeholder' => 'Custom Product Text Field',
'label' => __('Custom Product Text Field', 'woocommerce'),
'desc_tip' => 'true'
)
);

echo '





';

echo '
';
}

function woocommerce_product_custom_fields_save($post_id)
{
// Custom Product Text Field
$woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
if (!empty($woocommerce_custom_product_text_field))
update_post_meta($post_id, '_custom_product_text_field', esc_attr($woocommerce_custom_product_text_field));

// Custom Product Image Field
$woocommerce_custom_product_image_field = $_POST['_custom_product_image_field'];
if (!empty($woocommerce_custom_product_image_field))
update_post_meta($post_id, '_custom_product_image_field', esc_attr($woocommerce_custom_product_image_field));
}


This code will add a custom image field to the WooCommerce product creation panel. The field will allow users to upload an image for the product. The image URL will be saved as post meta data for the product.

Rate this post

4 of 5 based on 1925 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us