Skip to content
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
64 changes: 37 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
# WordPress Back-end Challenge

Desafio para os futuros programadores back-end em WordPress da Apiki.

## Introdução

Desenvolva um Plugin em WordPress que implemente a funcionalidade de favoritar posts para usuários logados usando a [WP REST API](https://developer.wordpress.org/rest-api/).

**Especifícações**:

* Possibilidade de favoritar e desfavoritar um post;
* Persistir os dados em uma [tabela a parte](https://codex.wordpress.org/Creating_Tables_with_Plugins);

## Instruções

1. Efetue o fork deste repositório e crie um branch com o seu nome e sobrenome. (exemplo: fulano-dasilva)
2. Após finalizar o desafio, crie um Pull Request.
3. Aguarde algum contribuidor realizar o code review.

## Pré-requisitos

* PHP >= 5.6
* Orientado a objetos

## Dúvidas

Em caso de dúvidas, crie uma issue.
# Favorite Posts

Plugin WordPress para favoritar posts via REST API.

## Descrição
Este plugin permite que usuários autenticados marquem ou desmarquem posts como favoritos utilizando uma rota customizada na REST API do WordPress. Os favoritos são armazenados em uma tabela personalizada no banco de dados.

## Instalação
1. Copie a pasta `favorite-posts` para o diretório `wp-content/plugins` do seu WordPress.
2. Ative o plugin pelo painel de administração do WordPress.

## Como funciona
- Cria a tabela `wp_favorite_posts` para armazenar os favoritos (usuário x post).
- Disponibiliza uma rota na REST API para favoritar/desfavoritar posts.
- Apenas usuários autenticados podem utilizar a funcionalidade.

## Endpoints da API

### Favoritar/Desfavoritar Post
- **Endpoint:** `/wp-json/favorite-posts/v1/toggle/{post_id}`
- **Método:** `POST`
- **Autenticação:** Necessária (usuário logado)
- **Parâmetros:**
- `post_id` (na URL): ID do post a ser favoritado/desfavoritado
- **Resposta:**
- `{ "status": "added" }` se o post foi favoritado
- `{ "status": "removed" }` se o post foi removido dos favoritos

#### Exemplo de requisição
```bash
curl -X POST \
-H "Authorization: Bearer <token>" \
https://seusite.com/wp-json/favorite-posts/v1/toggle/123
```

## Autor
Pedro Marcusso
16 changes: 16 additions & 0 deletions favorite-posts/favorite-posts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php
/**
* Plugin Name: Favorite Posts
* Description: Permite favoritar posts via REST API.
* Version: 1.0
* Author: Pedro Marcusso
*/

defined('ABSPATH') || exit;

$includes = plugin_dir_path(__FILE__) . 'includes/';
require_once $includes . 'install.php';
require_once $includes . 'functions.php';
require_once $includes . 'routes.php';

register_activation_hook(__FILE__, 'fp_create_favorites_table');
23 changes: 23 additions & 0 deletions favorite-posts/includes/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

function fp_toggle_favorite($data)
{
global $wpdb;

$user_id = get_current_user_id();
$post_id = (int) $data['post_id'];
$table_name = $wpdb->prefix . 'favorite_posts';

$exists = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table_name WHERE user_id = %d AND post_id = %d",
$user_id, $post_id
));

if ($exists) {
$wpdb->delete($table_name, ['id' => $exists]);
return ['status' => 'removed'];
} else {
$wpdb->insert($table_name, ['user_id' => $user_id, 'post_id' => $post_id]);
return ['status' => 'added'];
}
}
20 changes: 20 additions & 0 deletions favorite-posts/includes/install.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

function fp_create_favorites_table()
{
global $wpdb;

$table_name = $wpdb->prefix . 'favorite_posts';
$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT(20) UNSIGNED NOT NULL,
post_id BIGINT(20) UNSIGNED NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY user_post (user_id, post_id)
) $charset_collate;";

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta($sql);
}
11 changes: 11 additions & 0 deletions favorite-posts/includes/routes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

add_action('rest_api_init', function () {
register_rest_route('favorite-posts/v1', '/toggle/(?P<post_id>\d+)', [
'methods' => 'POST',
'callback' => 'fp_toggle_favorite',
'permission_callback' => function () {
return is_user_logged_in();
}
]);
});