• Hi,

    I was using the wp ajax call and got it to work. But I only encountered a problem when using the wp_insert_post. The post was created but the function does not return a postid. I put an echo in my function to return the postid but there is no response. Any ideas on what is causing this? This is my first time using the wp ajax call.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Thread Starter little_lulu

    (@littlu_lulu)

    Here is a sample of my code in php:

    add_action(‘wp_ajax_nopriv_my_action_restore_post’, ‘my_action_restore_post’);
    add_action(‘wp_ajax_my_action_restore_post’, ‘my_action_restore_post’);

    function my_action_restore_post(){

    $newPost = array(
    ‘post_content’ => ‘sample content’
    ,’post_name’ => ‘sample name’
    ,’post_title’ => ‘sample title’
    ,’post_status’ => ‘sample status’
    ,’post_type’ => ‘sample post type’
    ,’post_author’ => ‘sample author’
    ,’ping_status’ => ‘sample status’
    ,’post_parent’ => ‘sample parent’
    ,’post_password’ => ‘sample password’
    ,’post_excerpt’ => ‘sample excerpt’
    ,’comment_status’ => ‘sample comment status’
    );

    $post_id = wp_insert_post($newPost, true);

    echo $post_id;

    wp_die();
    }

    And here is my code in js file:

    var data = {
    ‘action’: ‘my_action_restore_post’,
    ‘restoreblogPostId’: blogPostArr
    }

    jQuery.ajax({
    type: “POST”,
    url: ajax_object.ajaxUrl,
    data: data,
    error: function(jqXHR, textStatus, errorThrown){
    alert(“error occured: ” + jqXHR);
    },
    success: function(data) {
    alert(data);
    }
    });

    Hi Lulu,

    You will have better results if you tell AJAX what type of data comes back from your function call. Here’s an example that returns JSON.

    function my_action_restore_post(){
    
    	$restored_post = whatever_you_need_to_do_here();
    	$response = array('post_id' => $restored_post, 'message' => 'The post restore was successful');
    
    	// send back JSON
    	$response = json_encode( $response  );
    	header( "Content-Type: application/json" );
    	echo $response;
    	exit;
    }
    Dion

    (@diondesigns)

    Your problem is the use of wp_die(), which sends an HTTP 500 error code to your browser. So instead of these two lines:

    echo $post_id;
    wp_die();

    You should do something like this:

    if (!empty($post_id)) {
    	 echo $post_id;
    }
    exit;

    In your JS, you should check whether the data variable is empty; if it is, then your call to wp_insert_post() failed.

    Thread Starter little_lulu

    (@littlu_lulu)

    Hi ancawonka and diondesigns,

    Thanks for your suggestions. I’ll try it and post again if works.

    Ah, thanks @diondesigns, I didn’t know about the HTTP 500 code from wp_die.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘wp_insert_post does not return postid in wp ajax call’ is closed to new replies.