How to create a blog using API ChatGPT and post create in WordPress

In this tutorial, I’m going to learn create a blog using API ChatGPT and post it in WordPress. so follow this tutorial in this tutorial we have mentioned it in a very easy way.

HTML Part :-

<h2>Blog Post Writer</h2>
    <form method="post">
        <input type="text" placeholder="TYPE HERE" name="str" required>
        <input type="submit" name="submit" value="Enter">
    </form>

PHP Code :-

<div class="container">
    <?php
    function convert_to_wp_block_markup($text) {
        // Escape special characters
        $text = htmlspecialchars($text);

        // Wrap the text in a paragraph block
        $markup = '<!-- wp:paragraph -->';
        $markup .= '<p>' . $text . '</p>';
        $markup .= '<!-- /wp:paragraph -->';

        return $markup;
    }

    // Rest of your code...


    if (isset($_POST['str'])) {
        $ch = curl_init();
        $str = $_POST['str'];
        curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        $search_Questions = [
            'What is ' . $str . '?',
            'Why ' . $str . '?',
            'How does ' . $str . ' work?',
            $str . ' architecture ?',
            'How to install and configure ' . $str .'?',
            'Basic tutorial of ' . $str .'?',
        ];

        $results = [];

        foreach ($search_Questions as $Question) {
            $postdata = array(
                "model" => "text-davinci-001",
                "prompt" => $Question,
                "temperature" => 0.4,
                "max_tokens" => 2000,
                "top_p" => 1,
                "frequency_penalty" => 0,
                "presence_penalty" => 0
            );
            $postdata = json_encode($postdata);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

            $headers = array();
            $headers[] = 'Content-Type: application/json';
            $headers[] = 'Authorization: Bearer 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';
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            $result = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Error: ' . curl_error($ch);
            }

            $result = json_decode($result, true);
            if (isset($result['choices']) && !empty($result['choices'])) {
                $answer = $result['choices'][0]['text'];
                $results[] = array('Question' => $Question, 'answer' => $answer);
            } else {
                // echo 'Error: Invalid API response';
            }
        }

        curl_close($ch);

        // Display the question-answer pairs
        foreach ($results as $result) {
            echo '<h3>' . $result['Question'] . '</h3>';
            echo convert_to_wp_block_markup($result['answer']); // Convert the answer to WordPress block markup
            echo '';
        }
        
        //-------------------------------------------Start WordPress coding part ----------------------------------------------------
        // Create a post in WordPress
        $username = 'admin';
        $password = 'your password';
        $rest_api_url = "http://localhost/wordpress/wp-json/wp/v2/posts";

        $data = array(
            'title'    => $search_Questions[0], // Use the first question as the post title
            'content'  => '', // Initialize the content variable
            'status'   => 'publish',
        );

        // Generate the content using the results
        
        $content = ''; // Initialize the $content variable
        foreach ($results as $result) {
            $content .= '<h3>' . $result['Question'] . '</h3>';
            $content .= convert_to_wp_block_markup($result['answer']); // Convert the answer to WordPress block markup
            $content .= '';
        }

        $data['content'] = $content;

        $data_string = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $rest_api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string),
            'Authorization: Basic ' . base64_encode($username . ':' . $password),
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);

        curl_close($ch);

        if ($result) {
            echo 'Post created successfully in WordPress!';
        } else {
            echo 'Error creating the post in WordPress.';
        }
    }
    ?>
</div>

Related Posts

How Predictive Monitoring Platforms Optimize Modern DataOps and Data Observability

Introduction Traditional monitoring systems are no longer equipped to handle this level of complexity. Legacy tools depend entirely on static thresholds, which flag problems only after a…

Read More

DataOps Integration Tools: A Guide to Seamless Data Pipeline Integration

Modern enterprise organizations generate vast quantities of information across dozens of isolated systems. Managing this distributed ecosystem requires engineering infrastructure that can ingest, process, and deliver data…

Read More

Transforming Global Healthcare Solutions with Expert Treatment Guidance

Introduction As healthcare networks expand globally, an increasing number of individuals look beyond their geographic borders for solutions. However, exploring foreign medical environments presents its own set…

Read More

Affordable Healthcare Secrets: How MyHospitalNow Helps Patients Find Verified Hospitals and Save Money

Introduction The single greatest hurdle in modern healthcare is the lack of transparent, centralized data. Comparing treatment costs across different institutions is notoriously difficult. A procedure that…

Read More

DataOps Security in Pipelines: Best Practices for Data Engineers

Data has become the primary asset of the modern enterprise, but it is also the most vulnerable. As organizations migrate from static data warehouses to distributed, real-time…

Read More

Evaluating Enterprise DataOps Tools for Secure Automation and Pipeline Orchestration

Introduction Enterprise data systems are expanding at an unprecedented rate. Organizations no longer manage just a few centralized databases. Instead, modern infrastructure spans across hybrid cloud environments,…

Read More