正确使用update_user_meta

时间:2017-03-20 19:43:49

标签: php jquery ajax wordpress

我很难理解如何正确使用update_user_meta。现在我有两个应该更新用户meta_key的函数。但是,theme_levels函数每次都可能会因为wp_head过滤器而覆盖ajax函数。还有更好的方法吗?

我的代码如下

function theme_levels() {

    $value = user_total_posts( get_current_user_id() )

    if( $value >= '0' && $value <= '499' ) {        
        $levels[] = array(
                'level'         => 'level-1',               
        );
        update_user_meta( $user_id, 'author_level', $levels );         
    } else {
        ...
    }
}
add_action( 'wp_head', 'theme_levels' ); 

然后我有一个ajax回调,它应该将另一个数组添加到同一个用户meta_key。

function ajax_callback() {  
    if( ! empty( $_POST['data-id'] ) ) {        
        $levels[] = array(
                'notification'  => sanitize_text_field( $_POST['data-id'] ),
        );      
        update_user_meta($user_id, 'author_level', $levels);        
    }

    wp_die();   
}
add_action( 'wp_ajax_theme_ajax', 'ajax_callback' );

这就是我想要的方式(var_dump上的$levels部分也是如此:

array(1) { 
    [0]=> array(2) { 
        ["level"]           => string(10) "level-1" // this will be added if user is logged in and reached the level
        ["notification"]    => string(28) "level-1-notification-read" // this should be added after the AJAX call
    } 
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您正在使用的$user_id未在任何地方定义。

请在开头使用功能theme_levels()ajax_callback()中的以下代码。

$current_user = wp_get_current_user();
$user_id=$current_user->ID;
相关问题