【问题标题】:How to obtain numeric value from a custom field by get_post_meta?如何通过 get_post_meta 从自定义字段中获取数值?
【发布时间】:2019-08-21 13:36:56
【问题描述】:

这可能是个愚蠢的问题,但最重要的是最常见的功能不起作用。

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

/**
 * 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。

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

【问题讨论】:

    标签: php wordpress get numbers custom-fields


    【解决方案1】:

    好的,这就是答案:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多