Wordpress woocommerce中get_post_meta的输出错误

Wordpress woocommerce中get_post_meta的输出错误,wordpress,woocommerce,Wordpress,Woocommerce,我正在尝试在woocommerce中添加自定义元数据库。它被完美地添加了。我的最终目标是在函数中调用该自定义字段,并在cart.php中显示它。所以我编码: 对于自定义字段:[我将在这方面参考 add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' ); // Save Fields add_action( 'woocommerce_proc

我正在尝试在woocommerce中添加自定义元数据库。它被完美地添加了。我的最终目标是在函数中调用该自定义字段,并在cart.php中显示它。所以我编码:

对于自定义字段:[我将在这方面参考

 add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
     // Save Fields
    add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

    function woo_add_custom_general_fields() {

     global $woocommerce, $post;

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

      woocommerce_wp_text_input( 
      array( 
        'id'  => 'number_field', 
        'label' => __( '<strong style="color:#239804">Your Free Products</strong>', 'woocommerce' ), 
        'placeholder' => '', 
        'description' => __( 'Please enter a number', 'woocommerce' ),
        'type' => 'number', 
        'custom_attributes' => array(
        'step'  => 'any',
        'min'   => '0'
                ) 
        )
        );

       echo '</div>';

      }//woo_add_custom_general_fields

      function woo_add_custom_general_fields_save( $post_id ){
      $woocommerce_number_field = $_POST['number_field'];
        if( !empty( $woocommerce_number_field ) )
        update_post_meta( $post_id, 'number_field', esc_attr( $woocommerce_number_field ) );

       }//woo_add_custom_general_fields_save( $post_id )
在我的cart.php中添加

<td class="product-quantity">
     <?php 

     echo free_products();
        ?>
   </td>

前端的输出变为零。有谁能帮我找出哪里出了问题。请提前感谢。

尝试以下代码:

    function free_products(){

    global $woocommerce ,$product, $post;

    foreach ( WC()->cart->get_cart() as $cart_item ) { 
    $my_var = $cart_item['product_id'];
    $free_number = get_post_meta( $my_var, 'number_field', true );


    $free_product = $cart_item['quantity'] * $free_number;

    echo apply_filters( 'woocommerce_cart_item_quantity', $free_product);       
            }   

        }

让我知道它是否对你有效。它对我有效。

谢谢@Rohil_PHPBeginner它有效。我现在明白了,实际上我错认为产品有效。问题是,检索数据时没有获取帖子ID。因此我们给出了产品ID,因为产品ID和帖子ID都是相同的。
    function free_products(){

    global $woocommerce ,$product, $post;

    foreach ( WC()->cart->get_cart() as $cart_item ) { 
    $my_var = $cart_item['product_id'];
    $free_number = get_post_meta( $my_var, 'number_field', true );


    $free_product = $cart_item['quantity'] * $free_number;

    echo apply_filters( 'woocommerce_cart_item_quantity', $free_product);       
            }   

        }