how to create favorite list in wordpress ?

Home » Snippets » how to create favorite list in wordpress ?
0

Created with:

Visibility: 

public

Creator: majed

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
// Add to favorites
function wpturbo_add_to_favorites($item_id) {
    $user_id = get_current_user_id();
    
    // Get the current list of favorites for the user
    $favorites = get_user_meta($user_id, 'wpturbo_favorites', true);
    
    // Add the new item to the list
    $favorites[] = $item_id;
    
    // Update the user meta with the new list of favorites
    update_user_meta($user_id, 'wpturbo_favorites', $favorites);
}

// Remove from favorites
function wpturbo_remove_from_favorites($item_id) {
    $user_id = get_current_user_id();
    
    // Get the current list of favorites for the user
    $favorites = get_user_meta($user_id, 'wpturbo_favorites', true);
    
    // Find the index of the item in the list
    $index = array_search($item_id, $favorites);
    
    // Remove the item from the list if it exists
    if ($index !== false) {
        unset($favorites[$index]);
        
        // Update the user meta with the updated list of favorites
        update_user_meta($user_id, 'wpturbo_favorites', $favorites);
    }
}

// Check if an item is in the favorites list
function wpturbo_is_favorite($item_id) {
    $user_id = get_current_user_id();
    
    // Get the current list of favorites for the user
    $favorites = get_user_meta($user_id, 'wpturbo_favorites', true);
    
    // Check if the item exists in the list
    return in_array($item_id, $favorites);
}
				

In this code, we have three functions:

To use these functions, you can call wpturbo_add_to_favorites() to add an item to the favorites list, wpturbo_remove_from_favorites() to remove an item from the favorites list, and wpturbo_is_favorite() to check if an item is in the favorites list.

Please note that this code assumes that you have a way to identify the items that you want to add to the favorites list, such as using their unique IDs. You will need to modify the code and integrate it into your specific WordPress theme or plugin to suit your needs.

Register an account to save your snippets or go Pro to get more features.