Firstly, I am a newbie when it comes to php. I have a plugin that periodically imports posts into my website. Normally, it should check if the post already exists, and if it does, it updates it. Otherwise it creates a new one. Now for some reason, it always takes the else path no matter what.

The if is like this:

if ( nmp_post_exists( $cam->username ) ) {

and the function is:

function nmp_post_exists($title) {
    global $wpdb;
    return $wpdb->get_row("SELECT * FROM wp_posts WHERE post_title = '" . $title . "'", 'ARRAY_A');
  • Have a look at get_page_by_title(), which, despite have page in its name, allows you to specify the post_type as a parameter (so you can search posts as well as any custom post type).
    – Pat J
    Aug 11, 2014 at 21:30
  • Is your table prefix wp_?
    – Milo
    Aug 11, 2014 at 21:30
  • No, my table prefix is different. That's what I am doing wrong? It's the name of the domain without the .com.
    – Stefan
    Aug 11, 2014 at 22:26
  • I am retarded. I am testing as we speak, I think it's my fault. I changed the default prefix for the database, and I wasted a day wondering what is wrong. Shall get back with results asap.
    – Stefan
    Aug 11, 2014 at 22:33

2 Answers 2


I suspect that PHP considers the value of $wpdb->get_row("SELECT * FROM wp_posts WHERE post_title = '" . $title . "'", 'ARRAY_A'); to be true no matter what (see also this). You'll have to count the number of rows that are returned

Try something like this instead:

$query = "SELECT COUNT(*) FROM wp_posts WHERE post_title = '$title'";
$count = $wpdb->get_var($query);
return $count > 0;
  • 1
    According to the codex the $wpdb->get_row returns "NULL" if nothing is found.
    – gdaniel
    Aug 11, 2014 at 20:12
  • Kasper, your choice did not work, still going only on the else path. But thanks for your time.
    – Stefan
    Aug 11, 2014 at 22:27

The code was working fine. My problem was that I forgot that I changed the default prefix of the database. Sorry guys for wasting your time. Have a good one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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