重复值保存

问题描述 投票:0回答:1

我在save_post动作上有这个代码:

add_action( 'save_post', 'product_price_changes' );

function product_price_changes( $post_id ) {

$post_type = get_post_type($post_id);

if ( 'product' == $post_type ) {

    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );

    if ( $is_autosave || $is_revision ) {
        return;
    }

    $regular_changes = get_post_meta ($post_id,'regular_changes',true);

    $regular_changes[] = array('test',35000);

    update_post_meta( $post_id, 'regular_changes', $regular_changes );

    }
}

每次保存任何产品时,我都想为现有数组添加一个数组。

但是这个代码每次都会向旧数组添加2次数组。

php arrays wordpress
1个回答
1
投票
You can apply if condition to avoid redundancy in the array.

我修改了你的代码。请使用它,我希望它能按照您的要求运行。

add_action( 'save_post', 'product_price_changes' );

function product_price_changes( $post_id ) {

$post_type = get_post_type($post_id);

if ( 'product' == $post_type ) {

    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );

    if ( $is_autosave || $is_revision ) {
        return;
    }

    $regular_changes = get_post_meta ($post_id,'regular_changes',true);
    $new_array = array('test',35000);
    $temp = 0;
    foreach($regular_changes as $changes){
    if(is_array($changes)){
    if(count(array_intersect($new_array, $changes)) == count($new_array)){
        $temp = 1;
        break;
     }
    }       
 }
    if($temp == 0){
       $regular_changes[] = $new_array;
    }

    update_post_meta( $post_id, 'regular_changes', $regular_changes );

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.