I need to use WordPress Rest API to delete a user and all its own (maybe custom) posts.
I tried to call <url_base>/wp/v2/users/<id> and I have to provide a further parameter ?reassign=USER_ID to reassign its posts to another user.
A silly solution should be adding a "garbage" user to the system and assign him all deleted posts. Then I can create a job to delete all posts. It seems a very stupid way to me.. :(
I just want to delete them. I can do it from WP admin panel... why I can't via Rest Api?
Thanks
EDIT
Passing "reassign" as an empty params (null is not accepted...) the API informs me that I'm not able to delete my own profile. I'm testing it as a subscriber (end user), but I need to be able to manage and delete my own data... Am I wrong?!
This is my solution... maybe not the best one, but it seems to work.
I added delete_users and remove_users capabilities to the Subscriber role (for my convenience).
My /DeleteUsers rest endpoint check for the user ID encrypted inside the JWT token that is sent in header and compare it with the user_id params. If they match, I can delete the user.
Now I just have to avoid that a user can access the WP Admin panel and make some mess!
This is the code:
function myDeleteProfile($data) {
require_once(ABSPATH.'wp-admin/includes/user.php');
$headers = getallheaders();
if(!isset($headers['Authorization']) || !$headers['Authorization']) {
return array('esito'=>'ko', 'descrizione'=>'Fail message!');
}
$jwt_parts = preg_split('/\./', $headers['Authorization']);
$jwt_decoded = json_decode(base64_decode($jwt_parts[1]));
$jwt_user = $jwt_decoded->data->user->id;
if( intval($data['user_id']) != intval($jwt_user) ) {
return array('esito'=>'ko', 'descrizione'=>'User cannot delete.');
}
else {
if( wp_delete_user($jwt_user,null) ){
return array('esito'=>'ok', 'descrizione'=>'Deleting...');
}
else {
return array('esito'=>'ko', 'descrizione'=>'Error.');
}
}
}
Related
I have a Dashboard Application in Webflow and I use Memberstack for User and Permissions.
Now the Issue I have is the following: I'm creating a new Memberstack User with Zapier, then I'm logging into Webflow with the new created User and it opens the Dashboard page. The Issue is, that I want, if a user loggs in for the first time, to redirect them to another page called "Onboarding".
My approach was to solve it in Memberstack, but it doesn't seem to work when I create the User with Zapier. Then I tried to find a solution in Webflow, to create a redirect if a Variable in the CMS Item is not set (For example "onboarding" = false).
Can someone help me to make this work?
Let me know if this works! I adapted some code I had which also will add the first time the member logged in to their Memberstack metadata.
Try adding this code before the site-wide </ body > tag:
<script>
MemberStack.onReady.then(async function(member) {
// if member is logged in
if(member.loggedIn){
var first_logged_in_timestamp = member["first-logged-in-timestamp"];
if(first_logged_in_timestamp === undefined || first_logged_in_timestamp == null || first_logged_in_timestamp.length < 1)
{ // set first-logged-in-timestamp
var first_logged_in_timestamp = timestamp;
member.updateProfile({
"first-logged-in-timestamp": timestamp,
}, false)
}
window.location.href='https://RedirectHereIfFirstLogIn.com';
}
else{
window.location.href='https://RedirectHereIfNotLoggedIn.com';
}
}
</script>
I am having the same problem here. It seems Memberstack doesn't have an off-the-shelf solution for that, but there are people setting timeouts to let Zapier to its thing before redirecting the user. As you can see right here:
https://forum.memberstack.io/t/member-specific-page-after-signup/1282
I've tried their suggestions in this post but they're not working.
I build a instagram widget in my wordpress theme. And now I want to do a website demo, I want to display some ins feeds of famous instagram authors with my access token. But it seems that I can only display my own instagram feeds with my access token and user id. why? is ins change its API? I saw some author at themeforest can still display different instagram feed of famous ins authors. Could you teach me how to do that?
To the first question. Yes, Instagram restricted access
Every new app created on the Instagram Platform starts in Sandbox
mode. Apps in this mode can use any API endpoint but are restricted to
a limited number of users and media. This is great for developing and
testing your app.
To go Live and fully access Instagram content, you will need to submit
your application for review and approval. Once reviewed, you will only
be able to request users the Permission Scopes for which your app was
approved. Because of this, your application may not be able to use
some API endpoints unless the corresponding permissions were reviewed
and approved.
But you can get feeds making calls to web-version with ?__a=1 parameter. In this case you recieve json. You need to write some code:
$otherPage = 'nasa';
$profileUrl = "https://www.instagram.com/$otherPage/?__a=1";
$iterationUrl = $profileUrl;
$tryNext = true;
$limit = 100;
$found = 0;
while ($tryNext) {
$tryNext = false;
$response = file_get_contents($iterationUrl);
if ($response === false) {
break;
}
$data = json_decode($response, true);
if ($data === null) {
break;
}
$media = $data['user']['media'];
$found += count($media['nodes']);
var_dump($media['nodes']);
if ($media['page_info']['has_next_page'] && $found < $limit) {
$iterationUrl = $profileUrl . '&max_id=' . $media['page_info']['end_cursor'];
$tryNext = true;
}
}
If you need only 12 media from one feed, your code can be simplier (without while). In both cases use $media to save a feed in your storage, then display it on your pages.
Please go through the instagram feed wordpress plugin https://wordpress.org/plugins/evm-social-gallery/, For instagram feed for wordpress website.
I am using the meteor package ian:accounts-ui-bootstrap-3 for accounts and alanning:roles for assigning roles.
On the sign up form I have two options one for Doctor and one for Advisor. I want to assign the selected option as a role to that user. Can someone let me know how to do this?
I have just started learning meteor and don't know much about its flow. I can assign roles to a user if I create the user manually like this:
var adminUser = Meteor.users.findOne({roles:{$in:["admin"]}});
if(!adminUser){
adminUser = Accounts.createUser({
email: "mohsin.rafi#mail.com",
password: "admin",
profile: { name: "admin" }
});
Roles.addUsersToRoles(adminUser, [ROLES.Admin]);
}
But I want to assign a roll automatically as a user signs up and select one of the options and that option should be assigned as his role.
You shouldn't need a hack for this. Instead of using Accounts.onCreateUser you can do it with the following hook on the Meteor.users collection. Something along the lines of the following should work:
Meteor.users.after.insert(function (userId, doc) {
if (doc.profile.type === "doctor") {
Roles.addUsersToRoles(doc._id, [ROLES.Doctor])
} else if (doc.profile.type === "advisor") {
Roles.addUsersToRoles(doc._id, [ROLES.Advisor])
}
});
To get around having to check on login every time it's possible to directly set the roles on the user object instead of using the Roles API.
A hack? Yep, you probably need to make sure the roles have already been added to roles... not sure if there's anything else yet.
if(Meteor.isServer){
Accounts.onCreateUser(function(options, user){
if(options.roles){
_.set(user, 'roles.__global_roles__', ['coach', options.roles]);
}
return user;
});
}
Note: _.set is a lodash method not in underscorejs.
There's no pretty solution because:
There's no server side meteor callback post complete account creation.
In onCreateUser the user hasn't been added to the collection.
Accounts.createUser's callback is currently only for use on the client. A method could then be used from that callback but it would be insecure to rely on it.
The roles package seems to grab the user from the collection and in onCreateUser it's not there yet.
you can use the Accounts.onCreateUser hook to manage that.
Please keep in mind the code below is fairly insecure and you would probably want to do more checking beforehand, otherwise anyone can assign themselves admin. (from docs):
options may come from an untrusted client so make sure to validate any values you read from it.
Accounts.onCreateUser(function (options, user) {
user.profile = options.profile || {};
if (_.has(options, 'role')) {
Roles.addUserToRoles(user._id, options.role);
}
return user;
});
Thanks for your response. I tried but it doesn't work for me.
I used Accounts.onLogin hook to to manage this. Below code works for me:
Accounts.onLogin(function (info) {
var user = info.user;
if(user.profile.type === "doctor"){
Roles.addUsersToRoles(user, [ROLES.Doctor])
}
else
if(user.profile.type === "advisor"){
Roles.addUsersToRoles(user, [ROLES.Advisor])
}
return user;
});
Is there any way that i can append my data into user global variable so i can access it on other pages?
You have two options
You can save it on the user object ($user->data), if it's some static data that doesn't change.
Use hook_user op load which could look like this:
function module_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'load':
$account->module = db_fetch_object(db_query(
'SELECT * FROM {module} WHERE uid = %d', $account->uid
));
break;
}
}
Hook user, is good if you have complex data that changes a lot. You can store the data in your own table, and append it you the user when it's being loaded. The downside is, that you will need to run user_load you get the data on the user object.
If you don't need/want to handle the storage of your data in the database because you just want it the be globally accessible during the user's session, you can store it in the $_SESSION array.
You can also use variable_set() and variable_get()if the data is common to all users else SESSIONS need to be used
I need to use Drupal 6's "hook_user" to update a 3rd party API whenever a user updates their profile.
Therefore I use the 'update' operation. The problem I am facing is that I just cannot see how I can stop execution if the 3rd party API update fails.
I.e. the user updates their username, but if the API fails, prevent Drupal from updating the local record.
function myhooks_user($op, &$edit, &$account, $category) {
switch ( $op )
{
case 'update':
if ( FALSE === updateAPI($data) )
{
drupal_set_message("Cannot update user information", "error", false);
return false;
}
break;
}
}
At the moment, the return false doesn't stop execution.
There is not a way to stop execution.
You should be able to overwrite $edit, with what's in the db. That way there wont be any change. I haven't tried this out, but it should work just fine.
Why do you want to do this anyways? You could just add a row in the db, and update the profile at a later time with cron instead, to avoid frustrated users that need to do the same edit over and over.