WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to check if the title exists before the wp_insert_post() is triggered.

However, the condition seems not to work as expected:

if( $wpdb->get_row("SELECT * FROM wp_posts WHERE post_title = '" . trim($titles_arr[$i]) . "' AND post_type=post", 'ARRAY_A') ) {
  // title do exist
  // don't save

} else {

  // ...perform save code


And it saves always no matter if it exists.

The funny part is that if the existing title i my db is e.g.: The best title in the world and slug the-best-title-in-the-world and for example one thing from the trim($titles_arr[0]) (I am looping the array via foreach loop) array than the slug of that post that shouldn't be saved in the first place is called the-best-title-in-the-world-2 and if I run my scirpt again it became the-best-title-in-the-world-3 etc.

share|improve this question
up vote 1 down vote accepted

use get_page_by_title to get post by title.

I check for it on my system

$post_exist=get_page_by_title( 'Hello world!', ARRAY_A, 'post' );
    if( ! empty( $post_exist ) ) {
          echo 'title exist';
    } else {
        echo 'title not exist';

Running successfully.

In your case it may be like

$post_exist=get_page_by_title( $title, ARRAY_A, 'post' );
if( ! empty( $post_exist ) ) {
      echo 'title exist';
} else {
    echo 'title not exist';

see also:Get WordPress Post ID from Post title

share|improve this answer
Please, can you be more specific how can I use get_page_by_title() in my code in a loop with my trim($titles_arr[$i]) and be aware that it has to be post (there are also attachments with the same name and this should be allowed; only the same title && post_type=post should by forbidden). – Derfder May 22 '13 at 11:54
@Derfder I am updating my answer check it – Ravinder Kumar May 22 '13 at 12:15
I am getting error Fatal error: Can't use function return value in write context – Derfder May 22 '13 at 12:56
Still not working. – Derfder May 22 '13 at 12:59
try it i am updating my answer may be problem with empty because get_page_by_title returning object, changed it to array ( try to check what output comes from empty( get_page_by_title( trim($titles_arr[$i], ARRAY_A, 'post' ) ) ) – Ravinder Kumar May 22 '13 at 13:03

Your Answer


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.