How adds the listing with ID 127 to the favorites of every new user upon registration

i make this but not working, on end is full code

  1. Hook into User Registration: The code uses the add_action function to hook into the hivepress/v1/models/user/register action, which is triggered when a new user registers.
  2. Define the Listing ID: It sets the ID of the listing that should be added to the user’s favorites. In this case, the listing ID is 127.
  3. Retrieve Current Favorites: It retrieves the current list of favorite listings for the newly registered user using the get_user_meta function. If the user has no favorites yet, it initializes an empty array.
  4. Add Listing to Favorites: It checks if the listing with ID 127 is already in the user’s favorites. If not, it adds the listing ID to the array of favorites.
  5. Update User Meta: Finally, it updates the user’s meta data with the new list of favorite listings using the update_user_meta function.

In summary, this code ensures that every new user will have the listing with ID 127 automatically added to their list of favorite listings upon registration.

what is bad?

add_action(
    'hivepress/v1/models/user/register',
    function($user_id, $values){
        $listing_id = 127; // ID of the listing to add as favorite
        
        // Get the current user's favorite listings
        $favorites = get_user_meta($user_id, 'hp_favorites', true);
        
        if (!$favorites) {
            $favorites = array();
        }
        
        // Add the listing to favorites if it's not already there
        if (!in_array($listing_id, $favorites)) {
            $favorites[] = $listing_id;
            update_user_meta($user_id, 'hp_favorites', $favorites);
        }
    },
    1000,
    2
);

Hi,

Favorites are stored as hidden comments of a custom type “hp_favorite”, where the author is set to the user ID and the post is set to the listing ID. You can then add a new favorite by inserting a new comment WordPress way (e.g. using wp_insert_comment) or HivePress way (by creating a new Favorite model object:

( new \HivePress\Models\Favorite() )->fill(
	[
		'user'    => $user_id_here,
		'listing' => $listing_id_here,
	]
)->save();

Hope this helps

Thanks a lot sir

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.