Prevent empty Post Title on form submit via front end post (wp_insert_post_)

I am creating a post from the front end using (shortened for brevity);

if (empty($_POST['my_title'])){  
    echo 'error: please insert a title';
} else {  
    $title =  $_POST['my_title'];
} 

$new_post = array(
'post_title'    => $title,
'post_status'   => 'publish',
'post_type'     => 'post'

$pid = wp_insert_post($new_post);   

If no Post Title is present on submit then the form returns the error message,

Read More

error: please insert a title

However WordPress still inserts the post with a title of (no title).

Is there a way through simple PHP validation to prevent wp_insert_post from accepting an empty value? (without using Javascript).

IMAGE

Related posts

Leave a Reply

2 comments

  1. Simply put the wp_insert_post call inside your conditional check so its only called if the post title is not empty, something like this:

    if (empty($_POST['my_title'])){  
        echo 'error: please insert a title';
    } else {  
        $title =  $_POST['my_title'];
        $new_post = array(
         'post_title'    => $title,
         'post_status'   => 'publish',
         'post_type'     => 'post');
        $pid = wp_insert_post($new_post);  
    }