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?
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With