【发布时间】:2018-09-04 22:15:16
【问题描述】:
我正在尝试执行以下操作:在产品页面中添加至少 3 个自定义文本字段,以便在保存时将它们全部显示或仅显示一两个。 我尝试了以下代码,但没有成功。当然,数据不会被保存,也不会显示。 :(
我哪里错了?
我试图通过将几个 sn-ps 混合在一起来实现我的目标:
// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
// Text Field #1
woocommerce_wp_text_input(
array(
'id' => '_text_field_1',
'label' => __( 'Campo aggiuntivo #1', 'woocommerce' ),
)
);
// Text Field #2
woocommerce_wp_text_input(
array(
'id' => '_text_field_2',
'label' => __( 'Campo aggiuntivo #2', 'woocommerce' ),
)
);
// Text Field #3
woocommerce_wp_text_input(
array(
'id' => '_text_field_3',
'label' => __( 'Campo aggiuntivo #3', 'woocommerce' ),
)
);
echo '</div>';
}
///
function woocommerce_product_custom_fields_save($post_id){
$woocommerce_custom_product_text_field_1 = $_POST['_text_field_1'];
if (!empty($woocommerce_custom_product_text_field))
update_post_meta($post_id, '_custom_product_text_field_1', esc_attr($woocommerce_custom_product_text_field_1));
$woocommerce_custom_product_text_field_2 = $_POST['_text_field_2'];
if (!empty($woocommerce_custom_product_number_field))
update_post_meta($post_id, '_custom_product_text_field_2', esc_attr($woocommerce_custom_product_text_field_2));
$woocommerce_custom_product_text_field_3 = $_POST['_text_field_3'];
if (!empty($woocommerce_custom_procut_textarea))
update_post_meta($post_id, '_custom_product_text_field_3', esc_html($woocommerce_custom_product_text_field_3));
}
///
add_action( 'woocommerce_before_single_product', 'custom_action', 15 );
function custom_action() {
// Display Custom Field Value
echo get_post_meta($post->ID, '_custom_product_text_field_1', true);
echo get_post_meta($post->ID, '_custom_product_text_field_2', true);
echo get_post_meta($post->ID, '_custom_product_text_field_3', true);
}
【问题讨论】:
标签: php wordpress woocommerce product custom-fields