php - 如何通过 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。
有任何想法吗?我错过了什么吗?
解决方案
好的,这就是答案:
$custom_cost = ceil(get_post_meta(get_the_id(), 'custom_cost_field', true));
对于自定义字段,请始终在函数中保留“get_the_id()”,它将起作用。这就是全部技巧 - 永远不要在其中保留变量(产品,帖子)。
如果您之前通过其他函数获得了 ID,它仍然无法工作 - 您必须在函数中保留“get_the_id()”。
推荐阅读
- java - Exact overload resolution procedure - why f(1) call against f(int... arg) and f(long... arg) is not ambiguous?
- batch-file - Psexec Log File to Mirror CMD Window Output
- python - getting 'NoneType' object has no attribute... immediately inside while loop, but not before
- c# - 带有 if 条件的多个 using 语句
- java - 如何验证序列中的 3 个数字是否相等?
- angular7 - get dom element by attribute in ionic 4
- python - Issues with compiling a Keras sequential model
- regex - 在关键字之前立即捕获引号中的文本
- docker - 无法 ping 到 Kubernetes 中工作节点的 Pod 的 IP
- php - Laravel 5.7 将我重定向到安装和系统要求