【问题标题】:Woocommerce: validate custom fields on my account edit pageWoocommerce:验证我的帐户编辑页面上的自定义字段
【发布时间】:2014-04-09 13:44:13
【问题描述】:
我需要在“编辑我的帐户”页面中验证并保存我的自定义字段。我在woocommerce/myaccount/form-edit-account.php 找到了这个页面的模板。我设法在这个模板文件中添加了我的自定义字段。现在我需要验证它们,如果一切正常 - 保存用户数据。
在这种情况下我需要使用什么钩子?我可以编辑class-wc-form-handler.php,但我不想。
谢谢
【问题讨论】:
标签:
php
wordpress
validation
woocommerce
【解决方案1】:
我发现了一个动作挂钩,可用于验证编辑帐户页面上的自定义字段或现有字段。
在functions.php中添加以下代码。
add_action('user_profile_update_errors','wdm_validate_custom_field',10,1);
function wdm_validate_custom_field($args)
{
if ( isset( $_POST['custom_field'] ) )
{
if(strlen($_POST['custom_field'])<6 )
$args->add( 'error', __( 'Your error message', 'woocommerce' ),'');
}
}
【解决方案2】:
可以使用此操作挂钩 woocommerce_save_account_details_errors 在编辑帐户页面验证自定义字段
【解决方案3】:
试试这个。
add_filter( 'woocommerce_process_myaccount_field_{your_custom_field_name}' , 'validate_edit_address' );
function validate_edit_address() {
$variable = $_POST['your_custom_field_name'];
if ( preg_match("/[ก-๙a-zA-Z]+$/", $variable ) ){
wc_add_notice( __( '<strong>Error</strong>' ), 'error' );
}
return $variable ;
}
例子:
add_filter( 'woocommerce_process_myaccount_field_billing_house_number' , 'validate_edit_address' );
function validate_edit_address() {
$variable = $_POST['billing_house_number'];
if ( preg_match("/[ก-๙a-zA-Z]+$/", $variable ) ){
wc_add_notice( __( '<strong>Error</strong>' ), 'error' );
}
return $variable ;
}