$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归因
scroll top