对订单中具有自定义元数据字段的产品进行计数

时间:2021-10-15 作者:arguad

我有一个wordpress插件,它按顺序对购买的产品进行计数,并用我的自定义元数据值进行标记。自定义元数据值以复选框的形式显示在产品页面中。我正在使用WooCommerce/WooCommerce订阅。

如果客户购买了5种产品,则会进行计数,然后将其存储在变量中。仅统计具有自定义元数据值复选框的产品。

计数不会发生,因为我相信在使用时不会检测到我的自定义元数据值复选框get_meta(); 在循环内。

Code below shows the metadata checkbox

/* Adding Extra field to product to Enable Traccar integration */

// Display Fields
add_action(\'woocommerce_product_options_general_product_data\', \'wootraccar_product_custom_fields_add\');
function wootraccar_product_custom_fields_add(){
    global $post;

    echo \'<div class="wootraccar_product_custom_field">\';

    // Custom Product Checkbox Field
    woocommerce_wp_checkbox( array(
        \'id\'        => \'_wootraccar_integration\',
        \'desc\'      => __(\'Check this box if Traccar integration is required for this product\', \'woocommerce\'),
        \'label\'     => __(\'Traccar Integration Required\', \'woocommerce\'),
        \'desc_tip\'  => \'true\'
    ));

    echo \'</div>\';
}

// Save Fields
add_action(\'woocommerce_process_product_meta\', \'wootraccar_product_custom_fields_save\');
function wootraccar_product_custom_fields_save($post_id){
    // Custom Product Text Field
    $wootraccar_integration = isset( $_POST[\'_wootraccar_integration\'] ) ? \'yes\' : \'no\';
        update_post_meta($post_id, \'_wootraccar_integration\', esc_attr( $wootraccar_integration ));
}

the for each loop

        $order = wc_get_order( $order_id );
        $email  = $order->get_billing_email();
        $name = $order->get_billing_first_name();

        $devicecount =0;

            foreach ( $order->get_items() as $item ) {
            if( $item->get_meta( \'_wootraccar_integration\', true )==\'yes\')
            {
                $devicecount = $devicecount +  $item->get_quantity();
            }
        }


1 个回复
最合适的回答,由SO网友:Freddy B 整理而成
{
    $userid="";
    $integration_status="";
      // Get an instance of the WC_Order object
        $order = wc_get_order( $order_id );
        $email  = $order->get_billing_email();
        $name = $order->get_billing_first_name();
        $items = $order->get_items();

        $devicecount =0;        

        foreach ( $items as $item ) {
            $product_name = $item->get_name();
            $product_id = $item->get_product_id();
            $product_variation_id = $item->get_variation_id();

            $productToBeIntegrated=get_post_meta($product_id,\'_wootraccar_integration\', true);
            //$integration_status.=$productToBeIntegrated;

            if ($productToBeIntegrated=="yes") {
                $devicecount = $devicecount +  $item->get_quantity();
                $integration_status.=$devicecount;          }
        }

相关推荐

当in_the_loop()为假时,何时以及为什么is_Single(‘my_cpt’)为真?

我正在使用模板系统的示例代码。此地址的页码:http://project.test/my_cpt/hello-post/.无法理解原因is_singular( \'my_cpt\' ) 是true 虽然in_the_loop() 是false.在页面模板中The Loop "E;“工程”:if ( have_posts() ) { while ( have_posts() ) { the_post(); ?>