11

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?

2 Answers 2

13

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 );

}
0
0

For Custom Post Type change the first line to:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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