1

I have a foreach loop inserting posts. And I already have statements to check if post already exists by unique meta values. But somehow, often when site is loading slowly, something strange happens and duplicated posts are appearing. Same permalink but just with "-2" and "-3" and so on in the end of the url.

I would like to know if there is a hook or something to stop the wp_insert_post() function from inserting the post if it detects that it has to add that to the permalink.

  • If you remove this then you end up with ambiguous URLs, slugs are unique for a reason, e.g. if 2 posts share the same slug test and you go to example.com/test how would WP know which one to load? – Tom J Nowell Jun 5 '18 at 15:19
  • 1
    Also note that post meta queries are exhorbitantly expensive and slow, it sounds like you have a locking problem/race conditions/concurrency issues – Tom J Nowell Jun 5 '18 at 15:20
  • @ Tom J Nowell I don't know if you maybe missunderstod me. I don't want two posts with the same URL. I want the second to never be created/inserted. – Peter Westerlund Jun 5 '18 at 17:25
0

You could add the additional check to your foreach loop to see if the post with exactly same slug as the one you're about to add already exists. Kinda difficult to tell exactly what you would have to do without seeing your current code.

I'm assuming you know the slug and a type of a post that you're trying to insert?

You could look up the existing post with that slug first:

$existing_item = get_page_by_path( 'your-post-slug', OBJECT, 'your_post_type');

// null means that there is no post with that slug
if ( null === $existing_item ) {
    // proceed with inserting a post 
}

Bear in mind that this would affect your page performance even more, as you're adding additional query to every item in the loop.

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.