更新发布元-检查值是否与之前相同

时间:2020-08-27 16:33:37

标签: wordpress

我正在更新一个post meta字段,并且可以使用下面的代码为我工作。现在,我想升级代码以检查新值是否与旧值相同

add_action( 'updated_post_meta', 'update_function', 10, 4 );
function update_function( $meta_id, $post_id, $meta_key, $meta_value )
{
    // check if $old_value == $new_value
}

我应该使用其他动作挂钩吗?旧值保存在哪里,新值保存在哪里?

1 个答案:

答案 0 :(得分:1)

为了获取post meta值,您应该使用get_post_meta($ post_id,'meta_key',true) 在这里get_post_meta from WordPress docs

了解更多信息

然后在函数中使用此代码应该可以解决您的问题

// not sure if you should use this action hook, maybe try a different trigger
// if u=you are updating user meta then use user_register hook to update user after 
registration

// hook that you are using is update_post_meta and not updated_post_meta
add_action( 'updated_post_meta', 'update_function', 10, 4 );
function update_function( $meta_id, $post_id, $meta_key, $meta_value )
{
  // get post meta value
  $old_value = get_post_meta($post_id, $meta_key, true);
  if($old_value == $new_value){
    return false;
  }else{
    return $new_value = update_post_meta($post_id, $meta_key, $updated_value);
  }
}
相关问题