Skip to content

Instantly share code, notes, and snippets.

@MaximeCulea
Last active September 6, 2017 09:17
Show Gist options
  • Save MaximeCulea/06b3a1d99f99295cc000ff087c9e8318 to your computer and use it in GitHub Desktop.
Save MaximeCulea/06b3a1d99f99295cc000ff087c9e8318 to your computer and use it in GitHub Desktop.
Allow users to edit their own comments through REST API.
<?php
add_filter( 'user_has_cap', 'bea_add_edit_comment', 10, 4 );
/**
* Allow users to edit their own comments
*
* @param array $allcaps An array of all the user's capabilities.
* @param array $caps Actual capabilities for meta capability.
* @param array $args Optional parameters passed to has_cap(), typically object ID.
* @param \WP_User $user The user object.
*
* @return mixed
*/
function bea_add_edit_comment( $allcaps, $caps, $args, $user ) {
// As working with REST Api only
if ( ! defined( 'REST_REQUEST' ) || true !== REST_REQUEST ) {
return $allcaps;
}
// Always allow the user to moderate comments
if ( in_array( 'moderate_comments', $caps ) ) {
$allcaps['moderate_comments'] = true;
return $allcaps;
}
// Only modify user capabilities if we are trying to edit a comment
if ( 'edit_comment' !== $args[0] ) {
return $allcaps;
}
/*
* We need to be sure we have three arguments
* $args[0] => the capability we want to allow for the user
* $args[1] => the current user id
* $args[2] => the current comment id
*/
if ( count( $args ) < 3 ) {
return $allcaps;
}
// We need a valid comment
$comment = get_comment( $args[2] );
if ( is_null( $comment ) ) {
return $allcaps;
}
/*
* We are checking if the current user are the one who wrote
* the current comment. If it's the case then add the required
* permissions for the edit process to succeed
*/
if ( Functions::user_can_manage_comment( $comment, $user->ID ) ) {
$allcaps['edit_others_posts'] = true;
$allcaps['edit_published_posts'] = true;
}
return $allcaps;
}
@MaximeCulea
Copy link
Author

MaximeCulea commented Sep 6, 2017

Hi @sharcupine, sorry for the delay ! I never get any notification for your answer.

You right, my bad I pasted it too quickly, in my code it was into a class, but when sharing on gist it should not be wrapped into a class, so I messed up ^^
Anyway I fixed my gist and now fully working, thx for the "issue" 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment