Created
February 22, 2020 14:05
-
-
Save isabellachen/7a67fe424ff1fd685a271bdef6050458 to your computer and use it in GitHub Desktop.
Create a Post with fetch in Wordpress with REST API and authentication with nonces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
const postData = { | |
title: 'Lorem ipsum dolor sit amet', | |
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', | |
status: 'publish' | |
}; | |
window | |
.fetch(`${scriptVars.endpoint}`, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'X-WP-Nonce': scriptVars.nonce | |
}, | |
credentials: 'same-origin', | |
body: JSON.stringify(postData) | |
}) | |
.then(() => window.alert('success')); | |
})(jQuery); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Shortcode Create Story | |
Description: Inserts Markdown editor and submit button to a post | |
*/ | |
add_shortcode('figment_create_story', 'figment_create_story_shortcode'); | |
function figment_create_story_shortcode() | |
{ | |
} | |
add_action('wp_enqueue_scripts', 'figment_enqueue_create_story_script'); | |
function figment_enqueue_create_story_script() | |
{ | |
/*Enqueue the styles and scripts the edit in markdown depends on*/ | |
wp_register_style('font_awesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css'); | |
wp_register_style('simple_mde_css', 'https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css'); | |
wp_enqueue_style('font_awesome'); | |
wp_enqueue_style('simple_mde_css'); | |
wp_enqueue_script('simple_mde_js', 'https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js', []); | |
/*Enqueue the file with the fetch request*/ | |
wp_enqueue_script('create-story-script', plugin_dir_url(__FILE__) . '/shortcode-create-story.js', ['jquery', 'simple_mde_js']); | |
/*Inject variables into the script, including the authentication nonce*/ | |
wp_localize_script('create-story-script', 'scriptVars', [ | |
'endpoint' => esc_url_raw(rest_url('wp/v2/posts/')), | |
'nonce' => wp_create_nonce('wp_rest') | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment