如何在遍历订单项时检查自定义复选框产品元的值

问题描述 投票:1回答:1

[我在Dokan new-single-product.php模板中创建了一个自定义复选框元:

<div class="dokan-form-group">
   <div class="dokan-input-group">
   <?php dokan_post_input_box( $post_id, '_custom_field', array( 'label' => __('Custom Checkbox','dokan') ), 'checkbox' ); ?>
  </div>

然后使用以下代码存储值:

add_action( 'woocommerce_product_options_general_product_data', 'wc_custom_add_custom_fields' );
function wc_custom_add_custom_fields() {
    global $woocommerce, $post;

   echo '<div class="options_group">';

  // Checkbox
    woocommerce_wp_checkbox( 
    array( 
        'id'            => '_custom_field',
        'label'         => __('Custom Field', 'woocommerce' )
        )
    );

  echo '</div>';
}

// Save Fields
add_action( 'dokan_process_product_meta', 'wc_custom_save_custom_fields' );
add_action( 'dokan_new_product_added', 'wc_custom_save_custom_fields' );
add_action( 'woocommerce_process_product_meta', 'wc_custom_save_custom_fields' );
function wc_custom_save_custom_fields($post_id) {

    $woocommerce_wccaf_precio_por_ = $_POST['_custom_field'];
    if( !empty( $woocommerce_wccaf_precio_por_) || empty( $woocommerce_wccaf_precio_por_))
        update_post_meta( $post_id, '_custom_field', esc_attr( $woocommerce_wccaf_precio_por_ ) );

}

现在,我希望逻辑是:遍历订购物料,如果物料已选中自定义复选框,则将物料行价格总计添加到$ amount变量中。这在订单完成时运行。

public function amount_total( $order_id ) {

                // Get Order
                $order   = wc_get_order( $order_id );
                $amount = 0;

                // Loop through order items
                $items = $order->get_items(); 

                foreach ( $order->get_items() as $item_id => $item ) {
                    $custom_field = $item->get_meta('_custom_field');
                    //$custom_field = wc_get_order_item_meta( $item_id, '_custom_field', true );
                //  $custom_field = get_post_meta( $item_id, '_custom_field', true );
                    $line_total = $item->get_total();

                    if( isset($custom_field) ) {
                        $amount += $line_total;
                    }
                }

我一直在尝试找到的每个解决方案,因此有3个不同的$ custom_field变量。但是什么都没用。

如果我检查产品编辑菜单中Dokan复选框中的元素,它将显示以下内容:screenshot

似乎有2个输入,其中1个隐藏。也许我应该尝试检索“已检查”属性而不是实际值?

php wordpress checkbox metadata isset
1个回答
1
投票

关于此的更多文章,我一直认为我的问题有所不同,但是我做了以下工作,并使用在其他帖子上找到的一般解决方案进行了修复:

  1. 已检查<的数据库中实际上存储了什么元值

  2. 已检查的get_post_meta方法的参数对该方法可读(在我的情况下$ item_id无效,该方法需要产品的实际帖子ID)]]

  3. 检查条件是否实际上使用了正确的值:if($ custom_field ==“ yes”)
  4. foreach函数的最终代码:

foreach ( $order->get_items() as $item_id => $item ) { $product_id = $item->get_product_id(); $custom_field = get_post_meta( $product_id, '_custom_field', true ); $line_total = $item->get_total(); if( $custom_field == "yes" ) { $amount += $line_total; } }

© www.soinside.com 2019 - 2024. All rights reserved.