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

Enterprise Delivery Pipelines: Technical Strategies for DevOps Training China

Introduction Software development teams frequently experience severe delivery bottlenecks when handoffs between developers and operations engineers rely on manual interventions. Code that runs reliably on a developer’s…

Read More

Inside the Overseas Work Visa for Indians: A Relocation Advisor’s Strategic Playbook

Indian professionals looking to build an international career quickly discover that finding an overseas job is only half the battle. Securing the legal right to work in…

Read More

The Vital Role of Digital Inclusion Programs in Advancing Modern Social Welfare

Introduction When local governments and public institutions digitize vital civic resources—from municipal court filings and welfare applications to public housing portals—they often assume the broader public can…

Read More

Best Weekend Events in Delhi: How to Find and Plan Outings

Introduction Being a student or an early-career creator in the capital means having endless curiosity but operating within realistic financial boundaries. You want to immerse yourself in…

Read More

Top DataOps Pipeline Testing Tools for Modern Data Teams

Introduction Modern data pipelines are complex distributed systems. A standard production workflow connects transactional databases, third-party APIs, object storage, streaming queues, transformation layers, cloud data warehouses, and…

Read More

Accelerating Pipeline Root Cause Analysis Using Telemetry and Graph Intelligence

Modern enterprise data architectures rely on an intricate web of batch jobs, streaming brokers, cloud warehouses, and SaaS APIs where standard task monitoring often falls short—a pipeline…

Read More