I am working on an API for a WordPress site. Basically, an external application (not made using WP) is able to send JSON to a file I made (api.php) and inside that file I load WP (using wp-load.php), and create a post (custom post type) based on the received JSON.

When I reach this block of code…

$formation_fr = wp_insert_post( array(
    'post_type' => 'formation',
    'post_title' => 'example post',
    'post_status' => 'publish',
    'post_author' => 2 // This is an admin account associated with this ID
) );

… the post gets created, and everything works except for the post_author (instead, there is no author for the post). But, my external application that sent the CURL request will receive this:

Error: call to URL http://domain.com/api/api.php failed with status 500, response
Alors, on triche ?
, curl_error , curl_errno 0`

The “Alors, on triche?” error is the “Cheatin’ uh?” error in French. WordPress for some reason thinks that I’m trying to circumvent capabilities.

If I try to log in the user (ID: 2) programmatically with this block of code…

private function login( $id )
{
    $wp_account = get_user_by( 'id', $id );
    $username = $wp_account->
    wp_set_current_user( $wp_account->ID );
    wp_set_auth_cookie( $wp_account->ID );
    do_action('wp_login', $username );
}

… then I get this:

Error: call to URL http://domain.com/api/api.php failed with status 500, response , curl_error , curl_errno 0

Which is basically the same error as above but without the “Cheanin’ uh?”. I didn’t expect that to work though, because AFAIK a cookie won’t affect a CURL connection.

So, how can I avoid running into capability errors when working over CURL? I’ve used wp_insert_post() many times before and never had this issue. My temporary hacky solution is to erase the wp_die() function, which fixes the issue obviously.

WordPress version is 3.9.1

Read more here: Authentication over CURL


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

,

Wordpress related questions and answers: