سؤال

$options = get_option('analytics');
if ( ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) {
    $options['analytics_startdate'] = '2018-12-01';
}

Why this is throwing an error :

Undefined index: analytics_startdate ,

though i am specifying it.

هل كانت مفيدة؟

المحلول

though i am specifying it.

You're not actually specifying it. You're trying to use it in your regex and THEN you specified it.

You can't use it in your "if" criteria when if it doesn't exist. You need to check to see if it exists first.

The following would set your value if it is not set OR if it IS set and doesn't match your regex:

$options = get_option( 'analytics' );
if ( ! isset( $options['analytics_startdate'] ) || ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) {
    $options['analytics_startdate'] = '2018-12-01';
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى wordpress.stackexchange
scroll top