I'm a beginner with WordPress plugin api, php and ajax. I'm coding a training plugin for myself to save posts article to read them later, like favourites on web browser, with folders.
I use oop to do so.
I assumed to create a new user meta called 'favoris', wich is an array with the users created folders.
I got something like that for getting favs, creating folders and deleting'em.
/** * Get favorites */ public function fp_ajax_getFav(){ $current_user = wp_get_current_user(); $userid = $current_user->ID; $folder = get_user_meta($userid, 'favoris'); $content = ''; $content .= 'Favoris'; $content .= ''; $content .= ''; $content .= ''; $content .= ''; if (!empty($folder)) { $content .= 'Tout supprimer'; $content .= 'Aucun favoris.'; } else{ $content .= 'Tout supprimer'; $content .= 'Aucun favoris.'; } $content .= ''; if (!empty($folder)) { $msg = ''; foreach ($folder as $key) { foreach ($key as $k => $value) { $content .= ' ' . ucwords($value['titre']) . ''; } } } else{ } $content .= ''; $content .= ''; return $content; } /** * Add folder */ public function fp_ajax_addFolder(){ $current_user = wp_get_current_user(); $userid = $current_user->ID; $meta = get_user_meta($userid, 'favoris'); if (empty($meta)) { if ($_REQUEST['foldername'] !== '') { $folder[0]['titre'] = $_REQUEST['foldername']; add_user_meta($userid, 'favoris', $folder); var_dump($folder); echo ucwords($_REQUEST['foldername']); die(); } } if (!empty($meta)) { $folder = $meta[0]; if ($_REQUEST['foldername'] != '') { foreach ($folder as $key => $value) { $i = count($folder); if ($value['titre'] != $_REQUEST['foldername']) { $folder[$i]['titre'] = $_REQUEST['foldername']; update_user_meta($userid, 'favoris', $folder); var_dump($folder); echo ucwords($_REQUEST['foldername']); die(); } } } } } /** * Remove folder */ public function fp_ajax_removeFolder(){ if ( ( !isset($_POST['folderId']) || empty($_POST['folderId']) ) && ( !isset($_POST['folderName']) || empty($_POST['folderName']) ) ) { echo 'Pas de dossier spécifié'; die(); } else{ $id = $_POST['folderId']; $name = $_POST['folderName']; $current_user = wp_get_current_user(); $userid = $current_user->ID; $folder = get_user_meta($userid, 'favoris'); $folderToErase = $folder[0][$id]; try { delete_user_meta($userid, 'favoris', $folder[0][$id]); echo $folderToErase['titre']; //print_r($folder[0][$id]['titre']); } catch (Exception $e) { echo 'not ok'; var_dump($folder); return $e->getMessage(); } die(); } }
As far as I get or create, everything goes fine. But when I want to remove a folder by key ($id), it doesn't. But when I echo the $folderToErase, the id's right.
Maybe some help ?
delete_user_meta()
is a meta value but you refer to it as a "key". Are you sure you are using the function correctly?var_dump($userid, 'favoris', $folder[0][$id]);
?$folder
stored in the database? Is it a serialized array?