I’m not sure you can do it directly using TinyMCE because it’s just an editor that modifies the content of the post being edited and does not affect the save operation itself. However, there’s a workaround.
The Workaround:
- Add a hidden field to the editing page.
- Modify it using the TinyMCE button
- Read it in
post_published_api_call
Adding the field
As mentioned here, using post_submitbox_misc_actions
hook you can add a field to the ‘Publish’ metabox. In your case you will add a hidden one as follows:
add_action( 'post_submitbox_misc_actions', 'wpse325418_my_custom_hidden_field' );
function wpse325418_my_custom_hidden_field() {
echo "<input id='i-am-hidden' name="publish-to-somewhere" type="hidden" />";
}
The TinyMCE button
The button will have one purpose, to set/clear the hidden field. Assuming your JS code is working, I’ll just modify the addCommand
part of it:
ed.addCommand('pb_button1', function() {
state = !state; /* Switching state */
ed.fire('pb_button1', {state: state});
if (state){
/* Button active */
document.getElementById("i-am-hidden").value = "1";
}
else {
/* Button inactive */
document.getElementById("i-am-hidden").value = "0";
}
});
Reading the field
Here we will modify your post_published_api_call
function to act based on the value of our hidden field:
function post_published_api_call( $ID, $post) {
if(!isset($_POST['publish-to-somewhere'])) return;
if($_POSt['publish-to-somewhere'] == '0') return;
$url = get_option('api_url', array('plugin_text_string' => DEFAULT_API_URL))['plugin_text_string'];
$title = $post->post_title;
$content = wp_post_to_html($post->post_content);
$post_data = array(
'status' => 'publish',
'title' => $title,
'content' => $content
);
$json_post = json_encode($post_data);
$data = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => $json_post,
'method' => 'POST'
));
}
add_action( 'publish_post', 'post_published_api_call', 10, 2);