You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义字段返回10NULL,需转换为整数的技术问题

解决WP自定义选项获取与整数转换问题

嘿,我一眼就看到问题所在啦!你之所以得到10NULL的输出,是因为用错了函数——bloginfo()是直接输出内容的,它不会把值返回给变量。当你执行$discount = bloginfo('discount');时,bloginfo会立刻把10打印出来,然后返回NULL给$discount,所以var_dump($discount)就会输出NULL,最终你看到的就是先打印的10加上NULL的var_dump结果,也就是10NULL。

正确的处理步骤

要获取wp_options里的自定义字段,得用WordPress专门的get_option()函数,它会返回对应的值而不是直接输出。然后再把返回的字符串转成整数,这里有几种简单可靠的方法:

方法1:强制类型转换

// 先获取自定义选项的值(返回字符串"10")
$discount = get_option('discount');
// 强制转换为整数
$discount_int = (int)$discount;
var_dump($discount_int); // 最终输出 int(10)

方法2:使用intval()函数

$discount = get_option('discount');
$discount_int = intval($discount);
var_dump($discount_int); // 同样输出 int(10)

方法3:带默认值的安全处理

如果担心字段不存在或者值为空的情况,可以给get_option加个默认值参数,避免转换出错:

// 字段不存在时默认返回0
$discount = get_option('discount', 0);
$discount_int = (int)$discount;
var_dump($discount_int);

额外提醒

bloginfo()是用来输出WordPress预设的站点信息(比如站点名称、网址、描述这些)的,并不适合获取自定义的wp_options字段,这是你最初踩的小坑~

内容的提问来源于stack exchange,提问作者Turan Zamanlı

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:36:20