Check if post of title already exists

I’m writing a plugin that takes an xml feed and posts it into WordPress using wp-cron

Everything is working dandy, except it keeps adding the same posts over again.

Read More

So, I’m working on a system to check to see if a post of that title already exists.

I’ve written this, but its always returning ‘already exists’

global $wpdb;
        $query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = %s', $article->heading);
        $wpdb->query( $query );

        if ( $wpdb->num_rows ) {
            error_log('already exists');
        } else {                
            wp_insert_post($post, $wp_error);
        }

I’m fairly new to working with the database side of WordPress and I saw the $wpdb when googling for help. Now, I haven’t defined this anywhere but the place I was reading seemed to suggest it was built in.

All help appreciated!

Thanks

Related posts

Leave a Reply

2 comments

  1. Yes $wpdb is built in and is loaded by the WordPress Core on every page load.

    I don’t see any critical problem with your code. I am going to suggest some improvements because I see some places where could go wrong, but mostly that should work. That makes me think that $article->heading is not matching up to the inserted post_title. So…

    Try to normalize your title with sanitize_title_with_dashes which is how WordPress builds the post slug, and then check for that slug instead.

    global $wpdb;
            $query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_name = %s', sanitize_title_with_dashes($article->heading));
            $cID = $wpdb->get_var( $query );
    

    Now your query is looking for post_name, which is the slug or permalink tail, and I changed $wpdb->query to $wpdb->get_var since you are looking for a single variable, which we save to $cID.

    Use a better check for your conditional.

    if ( !empty($cID) ) {

    However, this might not be the right approach at all. Look into the XML_RPC API mentioned by @kaiser. It has post insertion capabilities.