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,

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

2 Answers
2

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

Leave a Reply

Your email address will not be published. Required fields are marked *