Работаем над собственной системой комментариев WordPress.Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Работаем над собственной системой комментариев WordPress.

Сообщение Anonymous »

Проблема, с которой я столкнулся, заключается в том, что некоторые пользователи, например консультанты и члены команды, не имеют разрешения на использование формы комментариев или ее отправку, как это делают администраторы. Как предоставить этим пользователям доступ к оставлению комментариев в форме, аналогично администраторам, без получения ошибки: "Произошла ошибка. Повторите попытку.. Раздел комментариев для советника
Цель состоит в том, чтобы обойти эту проблему или найти решение. Заранее спасибо!
**Вот код из function.js
**

Код: Выделить всё

function enqueue_custom_scripts()
{
if (is_page_template('page-project-details.php')) {
wp_enqueue_script('jquery');
wp_enqueue_script('custom-comments', get_template_directory_uri() . '/js/custom-comments.js', array('jquery'), null, true);

// Localize script to pass AJAX URL
wp_localize_script('custom-comments', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

add_action('wp_ajax_post_comment', 'handle_comment_submission');

**//updated code line**

function handle_comment_submission()
{
// Verify the nonce for security
if (!isset($_POST['comment_nonce']) || !wp_verify_nonce($_POST['comment_nonce'], 'comment_nonce_action')) {
wp_send_json_error(['message' => __('Nonce verification failed', 'your-text-domain')]);
exit; // Stop processing if nonce is invalid
}

// Check if user is logged in
if (!is_user_logged_in()) {
wp_send_json_error(['message' => __('You need to be logged in to comment.', 'your-text-domain')]);
exit;
}

// Use a more general permission check for non-admin users
if (!current_user_can('edit_posts')) { // Or use any capability that your non-admin roles have
wp_send_json_error(['message' => __('You do not have permission to comment.', 'your-text-domain')]);
exit;
}

// Sanitize and get the comment
$comment = isset($_POST['comment']) ? sanitize_textarea_field($_POST['comment']) : '';
$project_id = isset($_POST['project_id']) ? intval($_POST['project_id']) : 0;

if (empty($comment) || $project_id  __('Invalid comment or project ID.', 'your-text-domain')]);
exit;
}

// Insert the comment into the database
global $wpdb;
$table_name = $wpdb->prefix . 'project_comments';

// Insert the comment
$wpdb->insert($table_name, [
'project_id' => $project_id,
'user_id' => get_current_user_id(),
'comment' => $comment,
]);

// Check for database insert error
if ($wpdb->last_error) {
wp_send_json_error(['message' => __('Database error: ' .  $wpdb->last_error, 'your-text-domain')]);
} else {
// Send a success response
wp_send_json_success(['comment' => esc_html($comment)]);
}
}
add_action('wp_ajax_post_comment', 'handle_comment_submission');
add_action('wp_ajax_nopriv_post_comment', 'handle_comment_submission'); // For non-logged-in users if needed
**вот настройки разрешений:
**

Код: Выделить всё

function add_comment_capabilities_to_roles()
{
// Get the administrator role
$admin_role = get_role('administrator');
if ($admin_role) {
$admin_role->add_cap('publish_comments', true); // Force add the capability
}

// Get the advisor role
$advisor_role = get_role('advisor');
if ($advisor_role) {
$advisor_role->add_cap('publish_comments', true); // Force add the capability
}

// Get the team_member role
$team_member_role = get_role('team_member');
if ($team_member_role) {
$team_member_role->add_cap('publish_comments', true); // Force add the capability
}

// Get the client role (if you want them to comment)
$client_role = get_role('client');
if ($client_role) {
$client_role->add_cap('publish_comments', true); // Force add the capability
}
}
add_action('init', 'add_comment_capabilities_to_roles');

**Вот Ajax
**

Код: Выделить всё

jQuery(document).ready(function ($) {
$('#project-comment-form').on('submit', function (e) {
e.preventDefault(); // Prevent default form submission

var formData =
$(this).serialize() +
'&comment_nonce=' +
$('input[name="comment_nonce"]').val();

$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: formData + '&action=post_comment', // Append action for AJAX
success: function (response) {
console.log(response); // Log the response to check its structure
if (response.success) {
$('#comments-list').prepend('
' + response.data.comment + '
');
$('#project-comment-form')[0].reset(); // Reset form
} else {
alert(
response.data && response.data.message
? response.data.message
: 'An error occurred. Please try again.'
);
}
},
});
});
});

**а вот код html и php:
**

Код: Выделить всё

Comments









Я попробовал обновить разрешения, которые давали пользователю доступ к просмотру формы, но теперь я не могу оставить комментарий как консультант или член команды, но могу оставить комментарий как администратор, потому что Я полагаю, что у администратора более высокое разрешение.

Подробнее здесь: https://stackoverflow.com/questions/790 ... ent-system
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»