Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers 2

up vote 4 down vote accepted

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);  
} 
share|improve this answer
    
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. –  userabuser May 8 '12 at 9:49
add comment

Or you could just

return;

after echoing the error. :)

share|improve this answer
    
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. –  userabuser May 9 '12 at 1:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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