首页 > 解决方案 > 通过 Ajax 更新用户元数据

问题描述

有人可以告诉我我在这里做错了什么吗?我有一个每隔几秒钟运行一次的 ajax 函数,它基本上检查 2 个数据库表,如果它们不匹配,则更新其中一个数据库表以匹配另一个数据库表,但由于某种原因,它不会更新数据库表。如何编辑该功能以便实现此目的?

以下是涉及的功能:

function tb_update_old_followers($user_id) {

    $followers = tb_get_follower_count($user_id);

    $old_followers = tb_get_old_follower_count($user_id);

    $response['new_new_followers'] = $followers;

    $response['old_new_followers'] = $old_followers;

    $response = json_encode( $response );

    echo $response;

    update_user_meta( $user_id, '_tb_old_followed_by_count', $followers + 1);

    die();
}
add_action('wp_ajax_tb_update_old_followers' , 'tb_update_old_followers');

function tb_get_follower_count( $user_id = null ) {

if ( empty( $user_id ) ) {
    $user_id = get_current_user_id();
}

$followed_count = get_user_meta( $user_id, '_tb_followed_by_count', true );

$count = 0;

if ( $followed_count ) {
    $count = $followed_count;
}

return (int) apply_filters( 'tb_get_follower_count', $count, $user_id );
}


function tb_get_old_follower_count( $user_id = null ) {

if ( empty( $user_id ) ) {
    $user_id = get_current_user_id();
}

$old_followed_count = get_user_meta( $user_id, '_tb_old_followed_by_count', true );

$old_count = 0;

if ( $old_followed_count ) {
    $old_count = $old_followed_count;
}

return (int) apply_filters( 'tb_get_old_follower_count', $old_count, $user_id );
}

任何帮助将不胜感激!

标签: javascriptphpajaxwordpressmeta

解决方案


原因很简单。您尚未在 tb_update_old_followers() 函数中定义 user_id 。只要去做,它就会奏效。

function tb_update_old_followers() {
    $user_id=get_current_user_id();

    $followers = tb_get_follower_count($user_id);

    $old_followers = tb_get_old_follower_count($user_id);

    $response['new_new_followers'] = $followers;

    $response['old_new_followers'] = $old_followers;

    $response = json_encode( $response );

    echo $response;

    update_user_meta( $user_id, '_tb_old_followed_by_count', $followers + 1);
    die();
}

推荐阅读