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
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();
}
]);
});