1

I have a custom PHP script which should get response from OpenAI API and build HTML article content from it and then push it to WP through wp_insert_post() function. When I do echo for the article it goes well but if I try wp_insert_post then every article will be created three times. But after consultation with my friend I still don't know why and I didn't find out any relevant answer.

Here is my code:

<?php
function sys_name2($string)
{
  $string = stripslashes($string);
  $origin = array(' – ', ' - ', 'ě', 'š', 'č', 'ř', 'ž', 'ý', 'á', 'í', 'é', 'ů', 'ú', 'ó', 'ď', 'ň', 'ť', 'Ě', 'Š', 'Č', 'Ř', 'Ž', 'Ý', 'Á', 'Í', 'É', 'Ů', 'Ú', 'Ó', 'Ď', 'Ň', 'Ť', '&nbsp;', ' ', '/', '�', ':', ')', '(');
  $new = array('-', '-', 'e', 's', 'c', 'r', 'z', 'y', 'a', 'i', 'e', 'u', 'u', 'o', 'd', 'n', 't', 'E', 'S', 'C', 'R', 'Z', 'Y', 'A', 'I', 'E', 'U', 'U', 'O', 'D', 'N', 'T', '-', '-', '-', '-', '', '', '');
  // $spec_chars=array('\'','\\',',','@','#','$','%','^','&','*','()');    

  $string = strtolower(str_replace($origin, $new, trim($string)));
  $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);

  return $string;
}
require_once( '../../wp-load.php' );

$curl = curl_init();    // create cURL session

$API_KEY = "sk-xxxx"; 
$games = [
            "Monopoly",
            "Pexeso",
            "GTA 3",
            "Blackjack",
            ];
            
$url = "https://api.openai.com/v1/chat/completions";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);

$headers = array( // cUrl headers (-H)
    "Content-Type: application/json",
    "Authorization: Bearer $API_KEY"
);
foreach($games as $hra) {
    $hraslug = sys_name2($hra);
    $article_title = $hra." recenze, torrent, HW požadavky";
    $html_content = "V článku <strong>".$hra." recenze, torrent, HW požadavky</strong> se dozvíte:<ul><li><a href='#".$hraslug."-recenze'>".$hra." recenze</a></li><li><a href='#".$hraslug."-torrent'>".$hra." torrent</a></li><li><a href='#".$hraslug."-hw-pozadavky'>".$hra." HW požadavky</a></li></ul><h2 id='".$hraslug."-recenze'>".$hra." recenze</h2>";
    //echo $html_content;
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    $prompt = 'Napiš mi recenzi na hru '.$hra.'.';
    $prompt_hw = "Vypiš mi HW požadavky ke hře '.$hra 've formátu raw html tabulky s border='1'.";

    $messages_review = array(
        array(
            "role" => "system",
            "content" => "Budu se tě ptát na recenze na různé hry, prosím vytvoř unikátní text recenze dané hry, můžeš použít inspiraci i z jiných webů. Při generování textů si hlídej skloňování, gramatiku a pravopis v českého jazyka."
            ),
        array(
            "role" => "user",
            "content" => $prompt
        )
    );

    $messages_hw = array(
        array(
            "role" => "system",
            "content" => "Budu se tě ptát na HW požadavky na různé hry, prosím vytvoř HTML tabulku s rámečkem (element table v tomto případě využívá atribut border s hodnotou 1), pokud nevíš HW požadavky k dané hře, najdi si hru na internetu a na různých stránkách jako například Steam můžeš HW požadavky k dané hře určitě najít."
            ),
        array(
            "role" => "user",
            "content" => $prompt_hw
        )
    );

    $review_data = array( // cUrl data
        "model" => "gpt-3.5-turbo", // choose your designated model
        "messages" => $messages_review, // choose your prompt (what you ask the AI)
        "temperature" => 0.5,   // temperature = creativity (higher value => greater creativity in your promts)
        "max_tokens" => 1024     // max amount of tokens to use per request
    );

    $hw_data = array( // cUrl data
        "model" => "gpt-3.5-turbo", // choose your designated model
        "messages" => $messages_hw, // choose your prompt (what you ask the AI)
        "temperature" => 0.5,   // temperature = creativity (higher value => greater creativity in your promts)
        "max_tokens" => 1024     // max amount of tokens to use per request
    );
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($review_data));

    $review_response = curl_exec($curl);               // execute cURL
    $review_response = json_decode($review_response, true);   // extract json from response
    //var_dump($review_response);

    $generated_text = $review_response['choices'][0]['message']['content'];  // extract first response from json
    $html_content .= $generated_text;
    $html_content .= "<h2 id='".$hraslug."-torrent'>".$hra." torrent</h2>Pokud hledáte ".$hra." torrent, buďte obezřetní ohledně virů, ideálně vždy před spuštěním torrent nahrajte na stránku virustotal.com která obsahuje databázi <a href='https://gamesquad.cz/nejlepsi-antivirove-programy/'>nejlepších antivirových programů</a>, čímž můžete pak snadno zkontrolovat přítomnost virů v torrentu. Pro větší bezpečnost však doporučujeme si hru ".$hra." koupit, opravdu to stojí za to, a koupí podpoříte vývojáře i v tom, aby vytvořili třeba další hru nebo nový obsah. Konkrétní ".$hra." torrent Vám tedy bohužel nenabídneme.<h2 id='".$hraslug."-hw-pozadavky'>".$hra." HW požadavky</h2>";
    //echo $html_content;   // output response

    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($hw_data));

    $hw_response = curl_exec($curl);               // execute cURL
    $hw_response = json_decode($hw_response, true);   // extract json from response
    //var_dump($hw_response);
    $generated_hw = $hw_response['choices'][0]['message']['content'];
    $html_content .= $generated_hw;
    
    $postData = array(
        'post_title' => $article_title,
        'post_status' => 'draft',
        'post_content' => $html_content,
        'post_author' => 1,
        'post_type'         =>   'post',
        'post_category' => array(55)
    );

    wp_insert_post($postData);
}
curl_close($curl);      // close cURL session*/

Do you have any ideas what I'm doing wrong?

2
  • 1
    Where does this code run? Are you requesting the file directly? Commented Jan 24 at 15:23
  • @JacobPeattie Hi, the code running in custom chatgpt folder in the /wp-content/ folder, so the way is /wp-content/chatgpt/chatgpt.php Commented Jan 24 at 16:49

1 Answer 1

0

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.

1
  • 1
    Hi, thank you so much, your answer helped me, that if solves everything! But I still can't understand why it solved this problem? Because if there is one foreach and this wp_insert_post is inside of it, why it gonna repeats three times? Commented Feb 11 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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