I'm getting the following PHP error's from Wordpress:
Warning: Cannot modify header information - headers already sent by (output started at domain/public_html/sdapi/wp-content/plugins/testpost/testpost.php:74) in domain/public_html/sdapi/wp-admin/post.php on line 235
Warning: Cannot modify header information - headers already sent by (output started at domain/public_html/sdapi/wp-content/plugins/testpost/testpost.php:74) in domain/public_html/sdapi/wp-includes/pluggable.php on line 1196
With this code:
<?php
/**
* Plugin Name: testpost
*/
add_action( 'publish_post', 'testpost', 10, 1 );
function testpost( $post ) {
// ***** Get variables *****
$post_id = $post;
$post_object = get_post( $post_id );
$post_object->post_content;
$title = $post_object->post_title;
$source_url = get_permalink( $post_id );
$body = $post_object->post_content;
$titleprint = preg_replace("/\r?\n/", "\\n", addslashes($title));
$bodyprint = preg_replace("/\r?\n/", "\\n", addslashes($body));
$posturlprint = preg_replace("/\r?\n/", "\\n", addslashes($source_url));
// ***** Run script *****
echo "<script>
var Request = new XMLHttpRequest();
Request.open('POST', '****POSTURL****');
Request.setRequestHeader('Content-Type', 'application/json');
Request.setRequestHeader('Accept', 'application/json');
Request.setRequestHeader('Authorization', '****TOKEN****');
Request.onreadystatechange = function () {
if (this.readyState === 4) {
}
};
var body = {
'article': {
'uuid': '090bda74-b021-4c7c-a44a-44f33bba32142',
'title': '". $titleprint ."',
'source_url': '". $posturlprint ."',
'body': '". $bodyprint ."'
}
};
Request.send(JSON.stringify(body));
</script>";
}
?>
*Whitespace before <?php
is added by pasting here, cannot get rid of it :(
At first I thought it was the Whitespace problem as explained extensively here: How to fix "Headers already sent" error in PHP.
Unfortunately that's not it (easy to fix) and I'm thinking it's the "Print, echo issue" as described in the same answer.
Unfortunately I need to use echo, otherwise my plugin doesn't work at all.
Is there an alternative for using echo here, or perhaps some way around this? Hope someone can help.