最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

options - How to check False booleans when using get_option?

programmeradmin2浏览0评论

Whenenver you do get_option( 'my_option' ) and that my_option is literally False itself, you cannot simply check for if( !get_option( 'my_option' ) ), to see if the value exists, because it'll return False and the check will be meaningless.

Is there no way to check whether or not the option key my_option exists?

Whenenver you do get_option( 'my_option' ) and that my_option is literally False itself, you cannot simply check for if( !get_option( 'my_option' ) ), to see if the value exists, because it'll return False and the check will be meaningless.

Is there no way to check whether or not the option key my_option exists?

Share Improve this question asked Oct 31, 2019 at 13:58 Daniel SmithDaniel Smith 617 bronze badges 2
  • A saved value for 'my_option' wouldn't literally be false, because booleans don't get stored in the database. update_option( 'my_option', false ); will save a value of '0', not false. So if you want to check if a value doesn't exist at all, do a strict check for === false. – Jacob Peattie Commented Oct 31, 2019 at 14:50
  • @JacobPeattie I've just tried to save an option as False and it doesn't even save anything, not 0...just nothing. The documentation for update_option specifies that the item must be serializable if it's non-scalar. Bools are scalars, so, it should handle the serialization...yet, if I save false, it doesn't get saved, if I save true, it gets converted to 1. When I read: core.trac.wordpress/ticket/40007 / it seems that get/update_option is really messed up and I should just rely on 0/1 to do my checks. – Daniel Smith Commented Nov 1, 2019 at 11:19
Add a comment  | 

1 Answer 1

Reset to default 3

You can set a default value for when the option does not exist. This way you can check to see if the returned value is false, or if it doesn't exist at all:

$value = get_option( 'my_option', $default_value );
if( $value == $default_value ) {
    // Option does not exist
} elseif ( $value == false ) {
    // Option's value is equal to false
}
发布评论

评论列表(0)

  1. 暂无评论