Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress wp_insert_post & wp_update_post

Tags:

wordpress

i would like to create a post from the front end of my wordpress site.

When people add posts with the same post_title i want that post to get updated, rather than creating a new post.

i have the following:

if (!get_page_by_title($post_title, 'OBJECT', 'post') ){
$my_post = array(
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_insert_post( $my_post );

}

else {

$page = get_page_by_title($post_title);
$page_id = $page->ID;

$my_post = array(

   'ID' =>  $page_id,
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_update_post( $my_post );

}

the above works fine until the post title is the same. It will still duplicate in the database and wont even consider the "else" statement.

Does the above look ok, or am i doing something wrong?

like image 825
danyo Avatar asked Jul 12 '13 14:07

danyo


1 Answers

What if you use the empty check for the array

Please be aware that it gets the first post/page item in the database even if the post is trashed.

$check_title=get_page_by_title($post_title, 'OBJECT', 'post');

//also var_dump($check_title) for testing only

if (empty($check_title) ){
$my_post = array(
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_insert_post( $my_post );

}

else {


$my_post = array(

   'ID' =>  $check_title->ID,
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_update_post( $my_post );

}
like image 169
M Khalid Junaid Avatar answered Oct 20 '22 11:10

M Khalid Junaid