Skip to content

Guilherme pontes #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
.likeImg{
display: inline-block;
width: 25px;
cursor: pointer;
transition: transform 0.6s ease-in-out;
}

.likeImg:hover {
transform: scale(1.6);
}

.alert{
position: relative;
padding: 0.75rem 1.25rem;
margin-bottom: 1rem;
border: 1px solid transparent;
border-radius: 0.25rem;
}

.alert-warning{
color: #145275;
background-color: #fff3cd;
border-color: #231d5c;
}

11 changes: 11 additions & 0 deletions img/star-active.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions img/star.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
76 changes: 76 additions & 0 deletions includes/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

// Função para adicionar um botão de "like" após o conteúdo do post.
function add_text_after_content($content) {
global $wpdb;
$post_id = get_the_ID();
$user_id = get_current_user_id();

$table_name = $wpdb->prefix . 'liked';

// Consulta para verificar se o usuário já curtiu o post.
$query = $wpdb->prepare("SELECT * FROM $table_name WHERE id_post = %d AND id_user = %d", $post_id, $user_id);
$already_liked = $wpdb->get_row($query);

$active = '';
$liked = 'false';
if($already_liked){
$active = '-active';
$liked = 'true';
}

if (is_singular('post')) {
if(!is_user_logged_in()){
$content .= "<div class='alert alert-warning'>Funcionalidade de like somente para usuários cadastrados</div>";
return $content;
}

$img_url = plugin_dir_url(dirname(__FILE__)) . "img/star$active.svg";
$img_html = '<div class="likeContainer"><img src="' . $img_url . '" class="likeImg" id="clickToLike" data-post-id="' . $post_id . '" data-user-id="' . $user_id . '" data-liked="' . $liked . '" alt="like"/></div>';
$content .= $img_html;
}

return $content;
}
add_filter('the_content', 'add_text_after_content');

// Função para registrar endpoints personalizados da REST API.
add_action('rest_api_init', function () {
register_rest_route('favorites/v1', '/toggle/', [
'methods' => 'POST',
'callback' => 'toggle_favorite',
'permission_callback' => function () {
return is_user_logged_in(); // Garante que apenas usuários logados possam acessar.
},
]);
});

// Função de callback para o endpoint da REST API.
function toggle_favorite(WP_REST_Request $request) {
global $wpdb;

$user_id = get_current_user_id();
$post_id = $request->get_param('post_id');

if (!$user_id || !$post_id) {
return new WP_REST_Response(['success' => false, 'message' => 'Dados inválidos'], 400);
}

$table_name = $wpdb->prefix . 'liked';

// Verifica se o post já foi favoritado pelo usuário.
$favorite = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table_name WHERE id_post = %d AND id_user = %d",
$post_id, $user_id
));

if ($favorite) {
// Se já estiver favoritado, remove.
$wpdb->delete($table_name, ['id_user' => $user_id, 'id_post' => $post_id]);
return new WP_REST_Response(['success' => true, 'message' => 'disliked'], 200);
} else {
// Caso contrário, adiciona como favorito.
$wpdb->insert($table_name, ['id_post' => $post_id, 'id_user' => $user_id]);
return new WP_REST_Response(['success' => true, 'message' => 'liked'], 200);
}
}
23 changes: 23 additions & 0 deletions includes/install.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

function create_custom_table() {
global $wpdb;

$nome_tabela = $wpdb->prefix . 'liked';

$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE IF NOT EXISTS $nome_tabela (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
id_post BIGINT(20) NOT NULL,
id_user BIGINT(20) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY user_post (id_user, id_post)
) $charset_collate;";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

dbDelta($sql);
}

register_activation_hook(__FILE__, 'create_custom_table');
37 changes: 37 additions & 0 deletions js/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
jQuery(document).ready(function ($) {
$(".likeImg").click(function () {
let postID = $(this).data("post-id");
let userID = $(this).data("user-id");
let liked = $(this).data("liked");

let data = {
post_id: postID,
user_id: userID,
};

$.ajax({
url: '/wp-json/favorites/v1/toggle/', // Usando o endpoint da REST API.
method: 'POST',
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', myAjax.restNonce); // Incluindo o nonce.
},
success: function (response) {
if (response.success) {
if (response.message === "disliked") {
$(".likeImg").attr("src", myAjax.imgUrl + "star.svg");
$(".likeImg").data("liked", "false");
} else if (response.message === "liked") {
$(".likeImg").attr("src", myAjax.imgUrl + "star-active.svg");
$(".likeImg").data("liked", "true");
}
} else {
alert(response.message);
}
},
error: function (response) {
alert('Ocorreu um erro ao processar sua solicitação.');
}
});
});
});
31 changes: 31 additions & 0 deletions like.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php
/*
Plugin Name: Favoritar posts
Description: Favoritar Post Wordpress para usuarios logados
Version: 1.0
Author: Guilherme Pontes
*/

function active_plugin() {
require_once plugin_dir_path(__FILE__) . 'includes/install.php';
create_custom_table();
}
register_activation_hook(__FILE__, 'active_plugin');

function enqueue_scripts() {
$plugin_dir = plugin_dir_url(__FILE__);

wp_enqueue_script('like-js', $plugin_dir . 'js/script.js', array('jquery'), '1.0', true);
wp_enqueue_style('like-style', $plugin_dir . 'css/style.css', array(), '1.0');

// Passar o nonce e outros parâmetros para o JavaScript.
$paths = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'imgUrl' => $plugin_dir . "img/",
'restNonce' => wp_create_nonce('wp_rest') // Gera o nonce para REST API.
);
wp_localize_script('like-js', 'myAjax', $paths);
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

require_once plugin_dir_path(__FILE__) . 'includes/functions.php';