0

i have just tried this

function myplugin_update_field_foo( $new_value, $old_value ) {
if ($newvalue !== $oldvalue && !empty($oldvalue)) {
    $newvalue = array_unique( array_merge( $newvalue, $oldvalue ) );
}
return $newvalue;
}

function myplugin_init() {
    add_filter( 'pre_update_option_ra_new_series_options', 'myplugin_update_field_foo', 10, 2 );
}

add_action( 'init', 'myplugin_init' );

and used this to show the result in the option page but not showing anything

        <?php $opt=get_option( 'ra_new_series_options', $default = false ); ?>
    <?php print_r($opt); ?>

1 Answer 1

0

You are misspelling the variables names. You define them as $new_value and $old_value with underscore that you forgot about.

Except this your code working fine.

function myplugin_update_field_foo( $new_value, $old_value ) {
    if ($new_value !== $old_value && is_array($old_value)  && is_array($new_value)) {
        $new_value = array_unique( array_merge( $new_value, $old_value ) );
    }
    return $new_value;
}

To get the option you use

$opt = get_option( 'ra_new_series_options' );

You can set default value if not exists like this:

$opt = get_option( 'ra_new_series_options', [1, 3] );

Another thing that you need to make sure that the $new_value and the $old_value is type array because if one of them is not your code will break.

If you want to merge different types (array, string, integer) you can do something like this:

add_filter( 'pre_update_option_ra_new_series_options', 'myplugin_update_field_foo', 10, 2 );
function myplugin_update_field_foo( $new_value, $old_value ) {
    $new_value_array = [];

    // Check if array and merge if not push into the array
    if( is_array( $new_value ) ) {
        $new_value_array = array_merge( $new_value_array, $new_value );
    } else {
        array_push( $new_value_array, $new_value );
    }

    if( is_array( $old_value ) ) {
        $new_value_array = array_merge( $new_value_array, $old_value );
    } else {
        array_push( $new_value_array, $old_value );
    }

    $new_value_array = array_unique( $new_value_array );

    return $new_value_array;
}
2
  • i already corrrect that but it's showing the new value only the old one not merged thanks Commented Sep 4, 2018 at 0:45
  • @AhmedRabea I notice you had a problem with the get_option() check my answer now.
    – Shibi
    Commented Sep 4, 2018 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.