[wp-trac] [WordPress Trac] #51699: The only correct method to check for existence of option

WordPress Trac noreply at wordpress.org
Tue Nov 3 12:08:00 UTC 2020


#51699: The only correct method to check for existence of option
--------------------------+-----------------------------
 Reporter:  ttodua        |      Owner:  (none)
     Type:  defect (bug)  |     Status:  new
 Priority:  normal        |  Milestone:  Awaiting Review
Component:  General       |    Version:
 Severity:  normal        |   Keywords:
  Focuses:                |
--------------------------+-----------------------------
 There are many valid cases to check if particular option exists in WP
 (checking for leftovers of other plugins, or existence of some theme
 options, or some other cases).

 The current advertised method to check that is:


 {{{
 if ( ! get_option('optionName') )
 }}}


 However, that is no way the correct approach as it is not able to check
 for option existence (because if the option is set with value:
 `null/false/0/empty-string`, then the check for existence will be
 meaningless with that approach).

 So, I suggest to add a correct function named `option_exists` to get the
 correct answer:

 {{{#!php
 function option_exists( $option_name, $site_wide = false ) {
         global $wpdb;
         return $wpdb->query( $wpdb->prepare( "SELECT * FROM ". ($site_wide
 ? $wpdb->base_prefix : $wpdb->prefix). "options WHERE option_name ='%s'
 LIMIT 1", $option_name ) );
 }
 }}}

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/51699>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list