The issue of your articles being created three times seems to be a result of the wp_insert_post() function being called multiple times. This typically happens when the code containing wp_insert_post() is executed more than once. Let’s analyze your code to identify potential causes and solutions.
Here’s an example of how you might check for existing posts:
foreach ($games as $hra) {
// ... [rest of your code] ...
$existing_posts = get_posts(array(
'title' => $article_title,
'post_type' => 'post',
'post_status' => 'draft',
'numberposts' => 1
));
if (count($existing_posts) == 0) {
wp_insert_post($postData);
} else {
// Post already exists, handle this scenario
}
}
This code snippet checks if there is already a draft post with the same title before inserting a new one. Adjust this logic based on your specific requirements, such as checking for published posts or using a different unique identifier.
Loop Execution: Your wp_insert_post() function is inside a foreach loop. Ensure that this loop only iterates once for each item in the $games array. If there’s any chance that the loop is executing more times than expected, this could be creating multiple posts.
Check for Existing Posts: Before inserting a new post, check if the post already exists to avoid duplicates. You can do this by querying posts with the same title or a unique identifier.
Code Execution Path: Ensure that your script is not being included or required multiple times in your application. This could inadvertently cause the whole script to run multiple times.
Error Handling: Add error handling to check the response of wp_insert_post(). If it’s failing for some reason, it might be retried unintentionally.
External Triggers: Make sure that your script is not being triggered multiple times from the outside, for example, by a cron job or an external application.
WordPress Actions and Filters: Sometimes, WordPress actions and filters can cause unexpected behavior. Ensure that there are no such hooks in your theme or plugins that might be affecting wp_insert_post().
Debugging: Add logging statements before and after wp_insert_post() to see how many times it’s being called. This can give you insights into where the problem might be.
CURL Calls: You are making CURL calls in the loop, ensure these calls are not affecting the loop’s logic or inadvertently causing the loop to reiterate.
To address these points, here’s a suggested approach:
Check for Duplicates: Before inserting a new post, check if a post with the same title already exists. If it does, skip the wp_insert_post() call.
Debugging: Add logging or debugging statements to check how many times your loop is running and how many times wp_insert_post() is called.
Code Review: Review your entire codebase for any possible re-inclusions of this script or unexpected triggers.