0

In my project there is a section: favorite. On posts there is a button to add to favorites when you click on this button,the post ID put on the current user metadata. This is the button code:

<span data-post-id="<?php the_ID(); ?>" data-user-id="<?php echo $current_user->ID; ?>" class="receipt_favorites"></span>

Here is the Jquery for ajax:

jQuery('.receipt_favorites').on('click',function(e){
    var postID = jQuery(this).attr("data-post-id");
    var userID = jQuery(this).attr("data-user-id");

    data = {
            'action': 'dicaprio_add_fav_recipe',
            'postID': postID,
            'userID': userID
        }
        jQuery.ajax({
            type:'post',
            url: object_url.url,
            data: data,
            cache: false,
            success: function(data) {
            }
        });
    e.preventDefault();
 });

And here is php:

add_action( 'wp_ajax_nopriv_dicaprio_add_fav_recipe', 'dicaprio_add_fav_recipe' );
add_action( 'wp_ajax_dicaprio_add_fav_recipe', 'dicaprio_add_fav_recipe' );

function dicaprio_add_fav_recipe() {

$postID = $_POST['postID'];
$userID = $_POST['userID'];

$current_fav_list = get_user_meta( $userID, 'favorite_list_recept', true );

if ( is_array( $current_fav_list ) ) {
    if ( in_array( $postID, $current_fav_list ) ) {

    } else {
        $current_fav_list[] = $postID;
    }
} else {
    $current_fav_list   = array();
    $current_fav_list[] = $postID;
}
update_usermeta( $userID, 'favorite_list_recept', $current_fav_list );
}

And this trinity does an excellent job, the post is added to favorites. But how can I remove it from favorites? It is my problem. I understand that for this I need to create a button like:

<span data-post-id="<?php the_ID(); ?>" data-user-id="<?php echo $current_user->ID; ?>" class="remove__favore"></span>

And use identical Jquery for ajax, only with activation by this class: remove__favore. But how about php function part? I thought it would be easier, but I couldn't write a function to delete favorite post. Can you tell me how to re-arrange the removal? I understand that for the pros this is a noob question, but I spent a lot of time and could not solve it.

Victor Sokoliuk
  • 435
  • 4
  • 17
  • Your data gets stored in an array, so you will need to find the array element holding the post id you want to remove from favorites - remove it from the array, and store the updated array to the meta data field again. – CBroe Nov 27 '20 at 07:54
  • @CBroe So, if I got it right. All I need: remove the data from the array. And update the data. It's really: at first I get all $current_fav_list = get_user_meta( $userID, 'favorite_list_recept', true ); and deleting an element from an array I remove the data I need. Greate, thanks I think I got it now. – Victor Sokoliuk Nov 27 '20 at 08:39

0 Answers0