首页 > 解决方案 > 如何通过 get_post_meta 从自定义字段中获取数值?

问题描述

这可能是一个愚蠢的问题,但微不足道的是最常见的功能无法工作。

通过这段代码,我设置了我的自定义字段:

/**
 * Extra custom fields
*/

function ccf_create_custom_field() {
 $args = array(
'id' => 'custom_cost_field',
'label' => __( 'Product Cost', 'woocommerce' ),
'class' => 'ccf-cost-field',
'type' => 'number',
);

woocommerce_wp_text_input( $args );
}

/* Display Fields */
add_action( 'woocommerce_product_options_general_product_data', 'ccf_create_custom_field' );


/* Save Fields */
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

function woocommerce_product_custom_fields_save($post_id) {

/* Custom Product Number Field */
$woocommerce_custom_product_number_field = $_POST['custom_cost_field'];
if (!empty($woocommerce_custom_product_number_field))
    update_post_meta($post_id, 'custom_cost_field', esc_attr($woocommerce_custom_product_number_field));
}

require_once "custom.php";

这是我的custom.php:

<?php while (have_posts()) : the_post(); ?>
<?php wc_get_template_part('content', 'single-product'); ?>
<?php

// Display the value of custom product number field
echo get_post_meta(get_the_ID(), 'custom_cost_field', true);
?>
<?php endwhile; // end of the loop. ?>

这是获取值的函数:

$costs = (ceil((get_post_meta($product, 'custom_cost_field', true))/100)*85);

尽管自定义字段保存了例如 1090 的值,但 get_post_meta 不返回任何内容,因为我的表中的值始终为 0 表示成本。我绝对不明白这一点:S。

有任何想法吗?我错过了什么吗?

标签: phpwordpressgetnumberscustom-fields

解决方案


好的,这就是答案:

$custom_cost = ceil(get_post_meta(get_the_id(), 'custom_cost_field', true));

对于自定义字段,请始终在函数中保留“get_the_id()”,它将起作用。这就是全部技巧 - 永远不要在其中保留变量(产品,帖子)。

如果您之前通过其他函数获得了 ID,它仍然无法工作 - 您必须在函数中保留“get_the_id()”。


推荐阅读