0

This is my code:

$my_post = array(
    'post_type'  => 'theposttt',
    'post_title'    => 'test',
    'post_content'  => '',
    'post_status'   => 'publish',
    'post_author'   => 1
);

$data = wp_insert_post($my_post);

ob_start();
get_template_part( 'template/the', 'post' );
$data = ob_get_clean();

$resp = array(
    'success'   => true,
    'msg'       => 'success',
    'data'      => $data
);

I want to get the post id of the new post from wp_insert_post to using it inside the template the-post.php that I get it by using the get_template_part function.

  • Would you please describe what you actually wanna accomplish ? Cause this way you can't create and show post in one file like this. At least not in any WP way. So please describe what you want actually and may be we can suggest a better way to do it ! – CodeMascot Nov 23 '17 at 4:16
1

Declare $my_post_id as global in your code. Declare $my_post_id as global in the-post.php template. Your code:

global $my_post_id;
$my_post = array(
    'post_type'  => 'theposttt',
    'post_title'    => 'test',
    'post_content'  => '',
    'post_status'   => 'publish',
    'post_author'   => 1
);
$my_post_id = wp_insert_post($my_post);
if(is_wp_error($my_post_id))
    $my_post_id = 0;

Now, you can use $my_post_id in the-post.php template. Possible values: 0 ( failure ), post id ( success ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.