【问题标题】:Save custom product input to database in WooCommerce将自定义产品输入保存到 WooCommerce 中的数据库
【发布时间】:2021-03-13 19:35:15
【问题描述】:

我对数据库使用如下代码:

$attribute_R_0 = wc_get_product( $post_id );
$title_top_R_0 = isset( $_POST['custom_text_field_title_related'] ) ? $_POST['custom_text_field_title_related'] : '';
$attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $title_top_R_0 ) );
$attribute_R_0->save();

但是我想使用一个条件来避免在db中创建一个空白表,哪个是正确的? A 还是 B?

答:

if ('custom_text_field_title_related') {
    $attribute_R_0 = wc_get_product( $post_id );
    $title_top_R_0 = isset( $_POST['custom_text_field_title_related'] ) ? $_POST['custom_text_field_title_related'] : '';
    $attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $title_top_R_0 ) );
    $attribute_R_0->save();
}

乙:

$attribute_R_0 = wc_get_product( $post_id );
$nui_1 = $attribute_14->get_meta( 'custom_text_field_title_related' );
if ($nui_1 ){
$title_top_R_0 = isset( $_POST['custom_text_field_title_related'] ) ? $_POST['custom_text_field_title_related'] : '';
$attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $title_top_R_0 ) );
$attribute_R_0->save();
}

【问题讨论】:

    标签: php wordpress validation woocommerce field


    【解决方案1】:

    没有一个...为了避免数据库表中出现空白条目,您应该改用:

    if ( isset( $_POST['custom_text_field_title_related'] ) && ! empty( $_POST['custom_text_field_title_related'] ) ) {
        $attribute_R_0 = wc_get_product( $post_id );
        $attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $_POST['custom_text_field_title_related'] ) );
        $attribute_R_0->save();
    }
    

    或更好:

    $field_key_R_0 = 'custom_text_field_title_related';
    
    if ( isset( $_POST[$field_key_R_0] ) && ! empty( $_POST[$field_key_R_0] ) ) {
        $attribute_R_0 = wc_get_product( $post_id );
        $attribute_R_0->update_meta_data( $field_key_R_0, sanitize_text_field( $_POST[$field_key_R_0] ) );
        $attribute_R_0->save();
    }
    

    【讨论】:

    • 感谢@LoicTheAztec,如果我有几个自定义输入,重复$attribute_R_0 = wc_get_product( $post_id ); 是否重要?
    • @M.SallarRabiei 对于属于该产品的所有相关产品输入,只有一次。你应该将$attribute_R_0命名为$product$_product
    • 我用的是第二种方法,但是当我删除文本框的时候,已经输入的内容并没有被删除。例如,当我添加一个产品时,我在复选框中输入,之后当我要删除它并更新产品信息时,我输入的文本仍然存在。
    • 我应该使用else {delete_post_meta( $id, 'custom_text_field_title_related' );} 吗?
    • 有效:else { $attribute_R_0 = wc_get_product( $post_id ); $attribute_R_0 = delete_post_meta( $post_id, 'custom_text_field_category_pills_4' ); }
    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2020-11-12
    • 2018-06-26
    • 1970-01-01
    • 2019-08-21
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多