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

How to check value of Custom Checkbox Product Meta when looping through order items

我在 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 个隐藏。也许我应该尝试检索属性 'checked' 而不是实际值?

关于这个还有几篇文章,我一直认为我的问题是不同的,但是我做了以下并用我在其他 posts 上找到的一般解决方案修复了它:

  1. 检查了元值实际存储在数据库中的元键

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

  3. 检查条件是否确实使用了正确的值:if( $custom_field == "yes" )

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;
                }
            }