在woocommerce中使用get_post_meta输出错误

时间:2014-12-26 11:18:29

标签: wordpress woocommerce

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

对于自定义字段:[我会在这方面提及http://www.remicorson.com/mastering-woocommerce-products-custom-fields/]

 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创建一个计数器

function free_products(){

global $woocommerce ,$product, $post;

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

$free_number = get_post_meta( $post->ID, 'number_field', true );

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

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

    }

在我的cart.php中添加

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

     echo free_products();
        ?>
   </td>

前端输出变为零。任何人都可以帮我解决我的错误。提前谢谢。

1 个答案:

答案 0 :(得分:2)

尝试以下代码:

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

        }

让我知道它是否适合你。它为我工作。