@anmkh

Как сделать реакции для поста без плагинов?

Нашел вот такое решение 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

}
  • Вопрос задан
  • 89 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы