thanks Lisa Cerilli, for the link I gave you a base on how to do it… I made some adjustments… but it helped a lot, follow my answer
in the front html it was like this/ php :here I list the post and the link to favorite
<?php while ( $list_plans->have_posts() ) : ?>
<?php $list_plans->the_post(); ?>
<div class="services__item ">
<div class="services__description">
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
<a href="<?php the_permalink (); ?>">Saiba mais</a>
<span class="add-to-fav">
<?php
$user_id = get_current_user_id();
$property_id = get_the_ID();
if(is_added_to_favorite( $user_id ,$property_id)) {
?>
<div class="fav-output show">
<i class="fa fa-star"></i>
<span class="fav-target">Added to Favourites</span>
</div>
<?php
} else {
?>
<a href="#add-to-favorite" id="post-<?php echo $property_id; ?>" value="<?php echo $property_id; ?>" class="add-to-favorite">
<i class="fa fa-star-o"></i>
<span id="<?php echo $property_id; ?>" class="<?php echo $user_id; ?>">Add to Favourites</span>
</a>
<?php
}
?>
</span>
</div>
</div>
<?php endwhile;?>
and here is the javascript to get the post and user id by ajax
<script >
jQuery(function ($) {
var property_id ;
var user_id ;
const favorite = (property_id , user_id) => {
$.ajax({
url: ajaxUrl,
type: 'POST',
data: {
action: 'add_to_favorite',
property_id,
user_id
},
}).done((response) => {
var property_id =null;
})
};
$("a.add-to-favorite").find("span").click(function(){
var property_id = $(this).attr("id");
var user_id = $(this).attr("class");
favorite(property_id, user_id );
});
});
</script>
and in functions.php I put the functions
function is_added_to_favorite( $user_id, $property_id ){
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM $wpdb->usermeta WHERE meta_key='favorite_properties' AND meta_value=".$property_id." AND user_id=". $user_id );
if( isset($results[0]->meta_value) && ($results[0]->meta_value == $property_id) ){
return true;
}else{
return false;
}
}
//ignora isto e so teste
function add_to_favorite(){
if( isset($_POST['property_id']) && isset($_POST['user_id']) ){
$property_id = intval($_POST['property_id']);
$user_id = intval($_POST['user_id']);
if( $property_id > 0 && $user_id > 0 ){
if( add_user_meta($user_id,'favorite_properties', $property_id ) ){
_e('Added to Favorites', 'framework');
}else{
_e('Failed!', 'framework');
}
}
}else{
_e('Invalid Paramenters!', 'framework');
}
die;
}
add_action('wp_ajax_add_to_favorite', 'add_to_favorite');
add_action( 'wp_ajax_nopriv_add_to_favorite', 'add_to_favorite' );