Как сделать реакции для поста без плагинов?
Нашел вот такое решение https://github.com/daveyheuser/WP-ajax-like-button..., но там только лайки. Пробую кастомизировать под дизлайки и нейтральную реакцию, ничего не выходит.
add_action('wp_ajax_like_callback', 'like_callback'); add_action('wp_ajax_nopriv_like_callback', 'like_callback'); function like_callback() { $id = json_decode($_GET['data']); // Get the ajax call $feedback = array("likes" => "", "dislikes" => ""); // Get metabox values $currentvalue = get_post_meta( $id, '_likers', true ); $likes = intval(get_post_meta( $id, '_likes_count', true )); $dislikes = intval(get_post_meta( $id, '_dislikes_count', true )); // Convert likers string to an array $likesarray = explode(', ', $currentvalue); // Check if the likers metabox already has a value to determine if the new entry has to be prefixed with a comma or not if(!empty($currentvalue)){ $newvalue = $currentvalue .', '. $_SERVER['REMOTE_ADDR']; }else{ $newvalue = $_SERVER['REMOTE_ADDR']; } // Check if the IP address is already present, if not, add it if(strpos($currentvalue, $_SERVER['REMOTE_ADDR']) === false){ $nlikes = $likes + 1; if(update_post_meta($id, '_likers', $newvalue, $currentvalue) && update_post_meta($id, '_likes_count', $nlikes, $likes)){ $feedback = array("likes" => likeCount($id), "status" => true); } if(update_post_meta($id, '_likers', $newvalue, $currentvalue) && update_post_meta($id, '_dislikes_count', $nlikes, $likes)){ $feedback = array("dislikes" => likeCount($id), "status" => true); } }else{ $key = array_search($_SERVER['REMOTE_ADDR'], $likesarray); unset($likesarray[$key]); $nlikes = $likes - 1; if(update_post_meta($id, '_likers', implode(", ", $likesarray), $currentvalue) && update_post_meta($id, '_likes_count', $nlikes, $likes)){ $feedback = array("likes" => likeCount($id), "status" => false); } if(update_post_meta($id, '_likers', implode(", ", $likesarray), $currentvalue) && update_post_meta($id, '_dislikes_count', $nlikes, $likes)){ $feedback = array("dislikes" => likeCount($id), "status" => false); } } echo json_encode($feedback); die(); // A kitten gif will be removed from the interwebs if you delete this line } |
add_action('wp_ajax_like_callback', 'like_callback'); add_action('wp_ajax_nopriv_like_callback', 'like_callback'); function like_callback() { $id = json_decode($_GET['data']); // Get the ajax call $feedback = array("likes" => "", "dislikes" => ""); // Get metabox values $currentvalue = get_post_meta( $id, '_likers', true ); $likes = intval(get_post_meta( $id, '_likes_count', true )); $dislikes = intval(get_post_meta( $id, '_dislikes_count', true )); // Convert likers string to an array $likesarray = explode(', ', $currentvalue); // Check if the likers metabox already has a value to determine if the new entry has to be prefixed with a comma or not if(!empty($currentvalue)){ $newvalue = $currentvalue .', '. $_SERVER['REMOTE_ADDR']; }else{ $newvalue = $_SERVER['REMOTE_ADDR']; } // Check if the IP address is already present, if not, add it if(strpos($currentvalue, $_SERVER['REMOTE_ADDR']) === false){ $nlikes = $likes + 1; if(update_post_meta($id, '_likers', $newvalue, $currentvalue) && update_post_meta($id, '_likes_count', $nlikes, $likes)){ $feedback = array("likes" => likeCount($id), "status" => true); } if(update_post_meta($id, '_likers', $newvalue, $currentvalue) && update_post_meta($id, '_dislikes_count', $nlikes, $likes)){ $feedback = array("dislikes" => likeCount($id), "status" => true); } }else{ $key = array_search($_SERVER['REMOTE_ADDR'], $likesarray); unset($likesarray[$key]); $nlikes = $likes - 1; if(update_post_meta($id, '_likers', implode(", ", $likesarray), $currentvalue) && update_post_meta($id, '_likes_count', $nlikes, $likes)){ $feedback = array("likes" => likeCount($id), "status" => false); } if(update_post_meta($id, '_likers', implode(", ", $likesarray), $currentvalue) && update_post_meta($id, '_dislikes_count', $nlikes, $likes)){ $feedback = array("dislikes" => likeCount($id), "status" => false); } } echo json_encode($feedback); die(); // A kitten gif will be removed from the interwebs if you delete this line }
Дополнительные вопросы
Привели исходный код из примера, а где Ваш код, как пробовали кастомизировать?
jQuery(document).ready(function ($) { $(".reaction") .stop() .click(function (e) { var rel = $(this).attr("rel"); var type = $(this).attr("data-type"); var data = { data: rel, action: "like_callback", post_action: type, }; $.ajax({ type: "GET", url: ajaxSite.ajaxurl, dataType: "json", data: data, success: function (data) { if (data.success == false) { alert("Вы уже поставили оценку"); } }, }); e.preventDefault(); }); }); |
jQuery(document).ready(function ($) { $(".reaction") .stop() .click(function (e) { var rel = $(this).attr("rel"); var type = $(this).attr("data-type"); var data = { data: rel, action: "like_callback", post_action: type, }; $.ajax({ type: "GET", url: ajaxSite.ajaxurl, dataType: "json", data: data, success: function (data) { if (data.success == false) { alert("Вы уже поставили оценку"); } }, }); e.preventDefault(); }); });
<?php add_action( 'wp_enqueue_scripts', 'ajax_scripts' ); function ajax_scripts() { wp_enqueue_script( 'ajax', get_template_directory_uri() . '/assets/js/ajax.js', array( 'jquery' )); wp_localize_script( 'ajax', 'ajaxSite', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action('wp_ajax_like_callback', 'reaction_callback'); add_action('wp_ajax_nopriv_like_callback', 'reaction_callback'); function set_cookie($type) { return setcookie($type, 'true', time() + (86400 * 365)); // 86400 = 1 день в секундах } function reaction_callback(){ $id = json_decode($_GET['data']); $post_action = isset($_GET['post_action']) ? $_GET['post_action'] : ''; $err_message = array(); $reactions = array( "likes" => "", "dislikes" => "", "neutrals" => "" ); $currentIp = get_post_meta( $id, '_likers', true ); $likesarray = explode(', ', $currentIp); $likes = intval(get_post_meta( $id, 'likes', true )); $dislikes = intval(get_post_meta( $id, 'dislikes', true )); $neutrals = intval(get_post_meta( $id, 'neutrals', true )); if($_COOKIE['reaction-'.$id.''] != true) { if($post_action == 'like') { update_post_meta($id, 'likes', $likes + 1, $likes); $reactions["likes"] = ["count" => $likes, "status" => true]; } elseif($post_action == 'dislike') { update_post_meta($id, 'dislikes', $dislikes + 1, $dislikes); $reactions["dislikes"] = ["count" => $dislikes, "status" => true]; } elseif($post_action == 'neutral') { update_post_meta($id, 'neutrals', $neutrals + 1, $neutrals); $reactions["neutrals"] = ["count" => $neutrals, "status" => true]; } echo json_encode($reactions); set_cookie('reaction-'.$id.''); } else { $err_message['cookie'] = 'Вы уже поставили оценку.'; wp_send_json_error( $err_message ); } die(); } |
<?php add_action( 'wp_enqueue_scripts', 'ajax_scripts' ); function ajax_scripts() { wp_enqueue_script( 'ajax', get_template_directory_uri() . '/assets/js/ajax.js', array( 'jquery' )); wp_localize_script( 'ajax', 'ajaxSite', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action('wp_ajax_like_callback', 'reaction_callback'); add_action('wp_ajax_nopriv_like_callback', 'reaction_callback'); function set_cookie($type) { return setcookie($type, 'true', time() + (86400 * 365)); // 86400 = 1 день в секундах } function reaction_callback(){ $id = json_decode($_GET['data']); $post_action = isset($_GET['post_action']) ? $_GET['post_action'] : ''; $err_message = array(); $reactions = array( "likes" => "", "dislikes" => "", "neutrals" => "" ); $currentIp = get_post_meta( $id, '_likers', true ); $likesarray = explode(', ', $currentIp); $likes = intval(get_post_meta( $id, 'likes', true )); $dislikes = intval(get_post_meta( $id, 'dislikes', true )); $neutrals = intval(get_post_meta( $id, 'neutrals', true )); if($_COOKIE['reaction-'.$id.''] != true) { if($post_action == 'like') { update_post_meta($id, 'likes', $likes + 1, $likes); $reactions["likes"] = ["count" => $likes, "status" => true]; } elseif($post_action == 'dislike') { update_post_meta($id, 'dislikes', $dislikes + 1, $dislikes); $reactions["dislikes"] = ["count" => $dislikes, "status" => true]; } elseif($post_action == 'neutral') { update_post_meta($id, 'neutrals', $neutrals + 1, $neutrals); $reactions["neutrals"] = ["count" => $neutrals, "status" => true]; } echo json_encode($reactions); set_cookie('reaction-'.$id.''); } else { $err_message['cookie'] = 'Вы уже поставили оценку.'; wp_send_json_error( $err_message ); } die(); }
Учим матчасть
Ответы на вопрос 0
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос
Реакции без плагина лучше делать не через GET и JSON в параметре, а через нормальный AJAX/REST-запрос с nonce, post_id и типом реакции. Хранить можно в post meta: отдельно счётчики
reaction_like,reaction_dislike,reaction_neutral.Пример AJAX:
add_action('wp_ajax_save_reaction', 'save_reaction'); add_action('wp_ajax_nopriv_save_reaction', 'save_reaction'); function save_reaction() { check_ajax_referer('reaction_nonce', 'nonce'); $post_id = absint($_POST['post_id'] ?? 0); $type = sanitize_key($_POST['type'] ?? ''); $allowed = ['like', 'dislike', 'neutral']; if (! $post_id || ! in_array($type, $allowed, true)) { wp_send_json_error(['message' => 'Bad request'], 400); } $key = 'reaction_' . $type; $count = (int) get_post_meta($post_id, $key, true); update_post_meta($post_id, $key, $count + 1); wp_send_json_success([ 'type' => $type, 'count' => $count + 1, ]); }
На фронте передавайте
post_id,typeиnonce. Чтобы один пользователь не накручивал реакции, храните выбор в cookie/localStorage или, лучше, в отдельной таблице/IP/user_id. Для простого блога cookie достаточно, но это не защита от накрутки.Важные детали:
Если реакции важны для рейтинга, лучше делать отдельную таблицу с уникальностью по post_id + user/session, а не просто увеличивать meta-счётчик.