在循环浏览订单商品时,无法检查是否在Dokan new-single-product.php中设置了Custom Checkbox Product Meta

问题描述 投票:0回答: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_ ) );

}

现在我希望逻辑是:浏览订单项,IF项目已选中自定义复选框,将项目行价格总计添加到$ 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 checkbox metadata isset
1个回答
0
投票

关于这一点还有更多的文章,我一直在想我的问题是不同的,但是我做了以下几点并使用我在其他帖子上找到的一般解决方案修复了它:

  1. 检查元数据库中实际存储的元值是什么。
  2. 检查get_post_meta方法的参数是可读的方法(在我的情况下$ item_id无效,该方法需要产品的实际帖子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;
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.