So I’ve built this theme so the client can add Properties to their WordPress website.
Within this theme I’ve built a favouriting system but I seem to be having a problem with making the favourite button work on the Custom Post Type list page.
The Problem:
Every time I hit the favourite button it will always favourite the first post in the list and not the one I clicked. Image Explain below:
In this Image it displays 3 of the Properties side by side with the star icon being the favourite button.
In this Image the first star is gone but I clicked the star on the far right Property.
My only thought is that in the jQuery I am not finding that Property ID and just finding an <i>
element and hiding it.
The jQuery code:
$('a#add-to-favorite').click(function(eve){
eve.preventDefault();
eve.stopPropagation();
var $star = $(this).find('i');
var add_to_fav_options = {
target: ('#fav-target'), // target element(s) to be updated with server response
beforeSubmit: function(){
$star.addClass('fa-spin');
}, // pre-submit callback
success: function(){
$star.removeClass('fa-spin');
$('#add-to-favorite').hide(0,function(){
$(this).find('#fav-output').delay(200).show();
});
}
};
$('#add-to-favorite-form').ajaxSubmit( add_to_fav_options );
});
The favourite code:
<span class="add-to-fav">
<?php
$property_id = get_the_ID();
if(is_added_to_favorite($property_id)) {
?>
<div id="fav-output" class="show">
<i class="fa fa-star"></i>
<span id="fav-target">Added to Favourites</span>
</div>
<?php
} else {
?>
<form action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" id="add-to-favorite-form">
<input type="hidden" name="property_id" value="<?php echo $property_id; ?>">
<input type="hidden" name="action" value="add_to_favorite">
</form>
<div id="fav-output">
<i class="fa fa-star"></i>
<span id="fav-target">Added To Favourites</span>
<span id="property-target-<?php echo $property_id; ?>" data-property-id="<?php echo $property_id; ?>"></span>
</div>
<a href="#add-to-favorite" id="add-to-favorite">
<i class="fa fa-star-o"></i>
<span class="add-to">Add to Favourites</span>
</a>
<?php
}
?>
</span>