通过AJAX从前端更新用户元数据,节省问题

时间:2018-03-03 作者:LWS-Mo

我想通过ajax从前端保存/更新自定义用户元字段。此字段应包含帖子ID列表。不允许使用双重ID。

我的问题是,每次更新字段值时,它都会被保存为多维数组。

例如,保存的数据如下所示:

Array ( [0] => Array ( [0] => Array ( [0] => [1] => 70 [2] => 79 ) [1] => 79 ) [1] => 93 )
我只需要/想要一个数组。

我尝试了不同的方法$single 的参数get_user_meta(), 似乎这就是问题所在。但我没能找到解决办法。

我想问题是我得到的值的格式get_user_meta().

在我的排队函数中,我使用wp_localize_script 向自定义JS文件添加值。在这里,我想检查是否已经保存了一个值,并将该值发送到JS文件。

(我在代码中添加了注释)

function my_custom_enqueue() {
    if ( is_user_logged_in() ) {

        wp_enqueue_script( \'ajax-script\', plugins_url(\'ajax.js\', __FILE__), array(\'jquery\') );

        $current_user = wp_get_current_user();
        $saved_ids = get_user_meta($current_user->ID, \'postlist\', false); 
        // if changed to true, jquery is not working anymore, but if true it can also be an array

        // do something if $saved_ids is empty ?! check if it is an array?!

        wp_localize_script( \'ajax-script\', \'my_ajax_object\', array( 
            \'ajax_url\' => admin_url( \'admin-ajax.php\' ),
            \'saved_ids\' => $saved_ids,
        ) );
    }
}
add_action( \'wp_enqueue_scripts\', \'my_custom_enqueue\' );
在我的ajax.js 文件:

jQuery(document).ready(function($){

    //get the $saved_ids value
    var postIdsToCompare = my_ajax_object.saved_ids;

    $(document).on(\'click\', \'.add-to-list\', function(e) {
        e.preventDefault();  

        // get post id from data-id of element
        var idToAdd = $(this).attr(\'data-id\');          

        // see if post id already exists in postIdsToCompare
        // this is not working anymore because of the multidimension arrays
        var found = $.inArray(idToAdd, postIdsToCompare);

        if (found >= 0) {
            // Element was found, remove it from array
            postIdsToCompare.splice(found, 1);
        } else {
            // Element was not found, add it to array
            postIdsToCompare.push(idToAdd);
        }

        var data = {
            \'action\': \'make_post_list\', // name of php function "wp_ajax_make_post_list"
            \'ids_to_compare\': postIdsToCompare, // to use $_POST[\'ids_to_compare\']
        };

        $.post(my_ajax_object.ajax_url, data, function(response) {
            alert(\'Added\');
        });
    });
});
我的ajax回调函数用于保存/更新字段。

add_action( \'wp_ajax_make_post_list\', \'make_post_list_callback\' );
function make_post_list_callback() {

    global $wpdb; // this is how you get access to the database

    // Ensure we have the data we need to continue
    if( ! isset( $_POST ) || empty( $_POST ) || ! is_user_logged_in() ) {
        exit;
    }

    $user_id = get_current_user_id();

    $saved_ids = get_user_meta($user_id, \'postlist\', true);

    $ids_to_compare = $_POST[\'ids_to_compare\'];

    //save user meta here
    update_user_meta(
        $user_id, // user id
        \'postlist\', // meta key
        $ids_to_compare, // meta value
        $saved_ids // prev value, tried without it also
    );

    wp_die();
}

1 个回复
SO网友:LWS-Mo

我想更新这个旧问题。

我成功了,或者至少我成功了。

感谢Tom J Nowell的支持。我考虑使用REST API是的,我看了一些介绍,但这超出了我的理解范围。RESTAPI和AJAX对我来说都是新的,我还没有真正使用过这些东西。我将特别研究RESTAPI的使用。

考虑到这一点,我认为代码可能会更好、更干净,但我只是在胡闹,认为无论如何我应该发布我的答案。它也有点像赤裸裸的骨头。。。

排队代码如下所示:

function my_custom_enqueue() {
    if ( is_user_logged_in() ) {

        wp_enqueue_script( \'ajax-script\', plugins_url(\'ajax.js\', __FILE__), array(\'jquery\') );

        wp_localize_script( \'ajax-script\', \'my_ajax_object\', array( 
            \'ajax_url\' => admin_url( \'admin-ajax.php\' ),
        ) );

    }
}
add_action( \'wp_enqueue_scripts\', \'my_custom_enqueue\' );
Theajax.js 文件如下所示:

jQuery(document).ready(function($){

    $(document).on(\'click\', \'.add-to-list\', function(e) {
        e.preventDefault();  

        // get post id from data-id of element
        var idToAdd = $(this).attr(\'data-id\');   

        var data = {
            \'action\': \'make_post_list\', // name of php function "wp_ajax_make_post_list"
            \'id_to_add\': idToAdd, // to use $_POST[\'ids_to_add\']
        };

        $.post(my_ajax_object.ajax_url, data, function(response) {
            console.log (response); // show response in console
            alert(response); // show response as alert
        });

    });

});
最后是回调函数:

function make_post_list_callback() {

    global $wpdb; // this is how you get access to the database

    // Ensure we have the data we need to continue
    if( ! isset( $_POST ) || empty( $_POST ) || !is_user_logged_in() ) {
        echo \'Oops! Try again.\';
        exit;
    }

    $user_id = get_current_user_id();

    // get array of already saved ID´s
    $saved_ids = get_user_meta($user_id, \'postlist\', true);

    // new ID to add to array
    $id_to_add = $_POST[\'id_to_add\'];

    // check if ID already exist in array,
    // only if it doesnt, we add it
    if( in_array( $id_to_add, $saved_ids ) ) {

        echo \'Failed: Post already in list.\';

    } else {

         //if list is empty, initialize it as an empty array
         if($saved_ids == \'\'){
            $saved_ids = array();
         }

        // push the new ID inside the array
        array_push( $saved_ids, $id_to_add );

        if ( update_user_meta( $user_id, \'postlist\', $saved_ids ) ) {
            echo \'Success!\';
        } else {
            echo \'Failed: Could not update user meta.\';
        }
    }

    wp_die(); // this is required to terminate immediately and return a proper response

}
add_action( \'wp_ajax_make_post_list\', \'make_post_list_callback\' );
通过此操作,登录用户可以单击帖子上的按钮,帖子ID将保存在用户的元数据中,保存的元数据如下所示:

Array ( [0] => 70 [1] => 76 [2] => 343 [3] => 375 [4] => 40 ) 

结束

相关推荐

AJAX响应错误|只是将错误作为响应

下面是AJAX文件的代码。alert(cont) 给出了正确的结果,但问题在于响应。我只是得到了错误的回应。function updateRadioButton(rating,pid){ var cont = rating + \'-\' + pid; alert(cont); jQuery.ajax({ type: \'POST\', url: TihomAjax.ajaxurl,