3

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

4

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);  
} 
1
  • You know I did this the first time around in my original code, but it did not work due to a typo so I've been hitting my head against a wall for 2hrs like a clown; thanks for reconfirming with the correct structure - appreciated.
    – Adam
    May 8, 2012 at 9:49
2

Or you could just

return;

after echoing the error. :)

1
  • 1
    That would've been my preferred choice but as soon as you return; you realize the script will halt at that point and not print the rest of the page.
    – Adam
    May 9, 2012 at 1:12

Your Answer

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

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