<?php
|
|
|
|
/**
|
|
* The public-facing functionality of the plugin.
|
|
*
|
|
* @link https://horizontes.info
|
|
* @since 1.0.0
|
|
*
|
|
* @package Reuna_Mailchimp
|
|
* @subpackage Reuna_Mailchimp/public
|
|
*/
|
|
|
|
use \DrewM\MailChimp\MailChimp;
|
|
|
|
/**
|
|
* The public-facing functionality of the plugin.
|
|
*
|
|
* Defines the plugin name, version, and two examples hooks for how to
|
|
* enqueue the public-facing stylesheet and JavaScript.
|
|
*
|
|
* @package Reuna_Mailchimp
|
|
* @subpackage Reuna_Mailchimp/public
|
|
* @author Horizontes Coop. <contato@horizontes.info>
|
|
*/
|
|
class Reuna_Mailchimp_Public {
|
|
|
|
/**
|
|
* The ID of this plugin.
|
|
*
|
|
* @since 1.0.0
|
|
* @access private
|
|
* @var string $plugin_name The ID of this plugin.
|
|
*/
|
|
private $plugin_name;
|
|
|
|
/**
|
|
* The version of this plugin.
|
|
*
|
|
* @since 1.0.0
|
|
* @access private
|
|
* @var string $version The current version of this plugin.
|
|
*/
|
|
private $version;
|
|
|
|
/**
|
|
* Initialize the class and set its properties.
|
|
*
|
|
* @since 1.0.0
|
|
* @param string $plugin_name The name of the plugin.
|
|
* @param string $version The version of this plugin.
|
|
*/
|
|
public function __construct( $plugin_name, $version )
|
|
{
|
|
$this->plugin_name = $plugin_name;
|
|
$this->version = $version;
|
|
}
|
|
|
|
/**
|
|
* Register the JavaScript for the public-facing side of the site.
|
|
*
|
|
* @since 1.0.0
|
|
*/
|
|
public function enqueue_scripts()
|
|
{
|
|
wp_enqueue_script($this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/reuna-mailchimp-public.js', array( 'jquery' ), $this->version, false);
|
|
|
|
wp_localize_script($this->plugin_name, 'wpApiSettings', [
|
|
'root' => esc_url_raw( rest_url() ),
|
|
'nonce' => wp_create_nonce( 'wp_rest' )
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Register REST API routes provided by the plugin
|
|
*
|
|
* @since 1.0.0
|
|
*/
|
|
public function register_rest_api_routes()
|
|
{
|
|
register_rest_route($this->plugin_name . '/v1', '/subscribe/(?P<list_id>\w+)', [
|
|
'methods' => 'POST',
|
|
'callback' => [$this, 'subscribe_user_to_list'],
|
|
'args' => [
|
|
'list_id' => [
|
|
'required' => true,
|
|
],
|
|
],
|
|
'permission_callback' => function () {
|
|
return current_user_can('read');
|
|
}
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Add a subscriber
|
|
*
|
|
* @since 1.0.0
|
|
*/
|
|
public function subscribe_user_to_list(WP_REST_Request $request)
|
|
{
|
|
if (! function_exists('env')) {
|
|
return new WP_Error('missing_env');
|
|
}
|
|
|
|
$api_key = env('MAILCHIMP_API_KEY');
|
|
if (! $api_key) {
|
|
return new WP_Error('missing_mailchimp_api_key');
|
|
}
|
|
|
|
$user = wp_get_current_user();
|
|
|
|
$mailchimp = new MailChimp($api_key);
|
|
$mailchimp->post(
|
|
'lists/' . $request->get_param('list_id') . '/members',
|
|
[
|
|
'email_address' => $user->user_email,
|
|
]
|
|
);
|
|
|
|
return true;
|
|
}
|
|
}
|