-
-
Save Ratko-Solaja/67d4443a471b8ef8445b436000d0bf0d to your computer and use it in GitHub Desktop.
Save or unsave the item.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Save or unsave the item. | |
* | |
* @since 1.0.0 | |
*/ | |
public function save_unsave_item() { | |
// Check the nonce, if ok, proceed. | |
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'toptal_save_nonce' ) ) { | |
die; | |
} | |
// Get the item ID from AJAX | |
if ( isset( $_REQUEST['item_id'] ) ) { | |
$item_id = intval( $_REQUEST['item_id'] ); | |
} else { | |
$item_id = 0; | |
} | |
$is_saved = false; | |
// Check if user is logged in | |
if ( is_user_logged_in() ) { | |
// Get all saved items for this user | |
$saved_items = get_user_meta( get_current_user_id(), 'toptal_saved_items', true ); | |
// Check if this user doesn't have any saved items | |
if ( empty( $saved_items ) ) { | |
$saved_items = array(); | |
} | |
// Check if this item is saved or not, if it is - unsave it, if it's not - save it | |
if ( in_array( $item_id, $saved_items ) ) { | |
$is_saved = true; | |
// Remove the item | |
unset( $saved_items[array_search( $item_id, $saved_items )] ); | |
} else { | |
$is_saved = false; | |
// Add the item | |
array_push( $saved_items, $item_id ); | |
} | |
// Save the changes to the user meta field | |
update_user_meta( get_current_user_id(), 'toptal_saved_items', $saved_items ); | |
} else { | |
// Get all saved items from the cookie | |
$saved_items = $this->toptal_get_cookie( $this->get_unique_cookie_name() ); | |
// Check if this item is saved or not | |
if ( in_array( $item_id, $saved_items ) ) { | |
$is_saved = true; | |
// Remove the item | |
unset( $saved_items[array_search( $item_id, $saved_items )] ); | |
} else { | |
$is_saved = false; | |
// Add the item | |
array_push( $saved_items, $item_id ); | |
} | |
// Save the changes to the cookie | |
$this->toptal_set_cookie( $this->get_unique_cookie_name(), $saved_items ); | |
} | |
// Create an array of data that we will return back to our AJAX | |
$return = array( | |
'is_saved' => $is_saved | |
); | |
// Return the data | |
return wp_send_json( $return ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment