Mike Hoogland
Mike Hoogland

Reputation: 3

Only post if it doesn't exist yet

I am building a plugin for Wordpress where I extract data from a XML feed and post all that data with the wp_insert_post() function. The plugin gets executed every hour so I have to prevent double posts.

I tried to add a filter and compare the post_date from the XML feed to the one in Wordpress (As I give the post the same post_date as the XML did), but it doesn't work and I can't figure out why..

Here's my code:

    add_filter('posts_where', 'checkPosts'); //I add a filter
    $query = new WP_Query('post_type=event'); // Make a query for the custom post_type 'event'
    if(!$query->have_posts()) { //If it doesn't have any posts with the same post_date post it
        $post_id = wp_insert_post($post);
        wp_set_object_terms($post_id, $genres, 'genre');
    }
    remove_filter('posts_where', 'checkPosts');

function checkPosts($where = '') {
    $where .= " AND post_date = ".$post_date;
    return $where;
}

Could someone show me my mistakes or give me another technique to prevent identical posts in Wordpress?

Upvotes: 0

Views: 119

Answers (2)

Mike Hoogland
Mike Hoogland

Reputation: 3

Alright, so if anyone is trying to do the same thing this is what worked for me.

I removed the filters because I'm not 100% sure how to use them and it can all be achieved much faster/easier with this method:

$query = new WP_Query('post_type=event&year='.$post_Y.'&monthnum='.$post_m.'&day='.$post_d.'&hour='.$post_H.'&minute='.$post_i);
    if(!$query->have_posts()) {
        $post_id = wp_insert_post($post);
        wp_set_object_terms($post_id, array( $venue_name ), 'locatie');
    }

Just fill in the year, monthnum, etc in with the information you want to use and that's it!

Upvotes: 0

Julio
Julio

Reputation: 2290

I'm not particularly familiar with Wordpress filters, but I do not believe the double equal sign is valid SQL.

Try changing your filter function:

function checkPosts($where = '') {
    $where .= " AND post_date = ".$post_date;
    return $where;
}

Upvotes: 1

Related Questions