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

Navigating Upcoming Events in Lucknow: Indie Stages, Concerts, and Art Spaces

Introduction Finding reliable, engaging activities across Lucknow often presents an unexpected challenge. Residents looking to unwind after a busy work week, college students seeking creative outlets, and…

Read More

Places to Visit in Bihar: An In-Depth Look at Regional History and Architecture

Introduction Planning a trip to eastern India often brings up questions about where to start, how connectivity works, and which heritage sites justify a visit. Bihar is…

Read More

Knee Replacement Surgery Guide: Symptoms, Surgical Options, and Physical Therapy

Introduction Persistent joint discomfort can disrupt everyday routines, making basic movements like climbing stairs, walking, or rising from a chair feel challenging. Finding effective knee treatment begins…

Read More

Complete Guide to Events in Kolkata: How to Discover What to Do

Finding something worthwhile to do across Kolkata often comes down to filtering noise rather than finding options. Between historic theatre corridors, contemporary auditorium programs, lively music venues,…

Read More

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