I wanted to update this older question.
I got this working or at least I got the saving worked out.
Thanks Tom J Nowell for your input. I considerd using the REST API yes, I looked at some introductions, but this went over my head.
The REST API but also AJAX is kinda new to me, and I havent really worked with these things. I will especially look into using the REST API.
With that in mind, I think the code could be a lot better and cleaner, but I was just playing around and thought I should post my answer anyway. Its also kinda bare-bones…
The Enqueue code looks like this:
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' );
The ajax.js
file looks like:
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
});
});
});
And finally the callback function:
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' );
With this a logged in user is able to click a button on a post, the post ID is than saved in the meta of the user, the saved meta data looks like:
Array ( [0] => 70 [1] => 76 [2] => 343 [3] => 375 [4] => 40 )