I have several old post which i want to revamp but rewriting them automatically using a plugin. i have formulated the code of the plugin but is not working well. te posts are not getting re-written. below is my code:
<?php
/**
* Plugin Name: Article Rewriter
* Description: A plugin to rewrite old posts of the "job" post type and show
progress, including detailed content changes, using AI Studio API.
* Version: 1.0
* Author: Your Name
*/
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
// Add a menu page in the admin panel
add_action('admin_menu', 'article_rewriter_menu');
function article_rewriter_menu() {
add_menu_page(
'Article Rewriter',
'Article Rewriter',
'manage_options',
'article_rewriter',
'article_rewriter_page',
'dashicons-edit',
20
);
}
// Display the plugin page
function article_rewriter_page() {
?>
<div class="wrap">
<h1>Article Rewriter</h1>
<p>This tool will rewrite old posts of the "job" post type using AI Studio
API.</p>
<form method="post">
<input type="submit" name="start_rewrite" class="button button-primary"
value="Start Rewriting Jobs">
<input type="submit" name="stop_rewrite" class="button button-secondary" value="Stop Rewriting Jobs">
<input type="submit" name="restart_rewrite" class="button button-secondary" value="Restart Rewriting Jobs">
</form>
<div id="progress-bar-container" style="margin-top: 20px; width: 100%;
background-color: #f3f3f3; height: 20px; border-radius: 5px; overflow: hidden;">
<div id="progress-bar" style="width: 0%; height: 100%; background-color: green;"></div>
</div>
<div id="progress-status" style="margin-top: 10px;"></div>
<div id="processed-posts" style="margin-top: 20px;">
<h3>Processed Posts:</h3>
<ul id="post-list"></ul>
</div>
<div id="all-processed-posts" style="margin-top: 30px;">
<h3>Posts That Have Been Processed</h3>
<table class="widefat fixed" cellspacing="0">
<thead>
<tr>
<th scope="col" class="manage-column">Post ID</th>
<th scope="col" class="manage-column">Title</th>
<th scope="col" class="manage-column">Status</th>
<th scope="col" class="manage-column">Date</th>
</tr>
</thead>
<tbody>
<?php article_rewriter_list_processed_jobs(); ?>
</tbody>
</table>
</div>
</div>
<?php
// Handle the post request to start, stop, or restart the rewriting process
if (isset($_POST['start_rewrite'])) {
article_rewriter_start();
} elseif (isset($_POST['stop_rewrite'])) {
article_rewriter_stop();
} elseif (isset($_POST['restart_rewrite'])) {
article_rewriter_restart();
}
// Display current progress status
article_rewriter_display_status();
}
// Start the rewriting process
function article_rewriter_start() {
// Initialize/reset the progress and processed posts
set_transient('article_rewriter_status', ['start' => 0, 'is_running' => true, 'batch_size' => 10]);
set_transient('article_rewritten_posts', []); // Track processed posts
article_rewriter_process_batch(0);
}
// Stop the rewriting process
function article_rewriter_stop() {
// Update status to stopped
set_transient('article_rewriter_status', ['is_running' => false]);
echo "<script>alert('Rewriting process has been stopped.');</script>";
}
// Restart the rewriting process
function article_rewriter_restart() {
// Reset progress and processed posts, and restart from the beginning
delete_transient('article_rewriter_status');
delete_transient('article_rewritten_posts');
article_rewriter_start();
}
// Display the current status of the rewriting process
function article_rewriter_display_status() {
$status = get_transient('article_rewriter_status');
if ($status && $status['is_running']) {
// Show progress bar and status
$start = $status['start'];
echo "<script>document.getElementById('progress-status').innerHTML = 'Rewriting job posts... " . $start . " of 100';</script>";
} else {
echo "<script>document.getElementById('progress-status').innerHTML = 'Process has stopped or not started yet.';</script>";
}
}
// Process the job posts in batches
function article_rewriter_process_batch($start = 0, $batch_size = 10) {
// Query for job posts with pagination (batching)
$args = array(
'post_type' => 'job',
'posts_per_page' => $batch_size,
'post_status' => 'publish',
'offset' => $start, // Start from the current batch
);
$jobs = new WP_Query($args);
$total_posts = $jobs->found_posts;
// If there are posts to update
if ($jobs->have_posts()) {
$updated_posts = [];
foreach ($jobs->posts as $post) {
// Original content of the post
$original_content = $post->post_content;
// Call the AI API to rewrite the content
$new_content = call_ai_rewrite_api($original_content);
// Use the AI API to update the post content
if (!empty($new_content) && $new_content !== $original_content) {
// Example rewrite logic: Modify the post title and content
$new_title = $post->post_title . ' - Updated';
// Save original title and content for tracking changes
$original_title = $post->post_title;
// Update the post with the new rewritten content
wp_update_post(array(
'ID' => $post->ID,
'post_title' => $new_title,
'post_content' => $new_content
));
// Track the changes (Title and Content)
$updated_posts[] = [
'ID' => $post->ID,
'original_title' => $original_title,
'new_title' => $new_title,
'original_content' => $original_content,
'new_content' => $new_content,
'link' => get_permalink($post->ID), // Include the post's link
'content_changes' => get_content_changes($original_content,
$new_content)
];
// Store the processed post ID in transient
$processed_posts = get_transient('article_rewritten_posts');
$processed_posts[] = $post->ID;
set_transient('article_rewritten_posts', $processed_posts);
}
}
// Update progress and save the batch number
$progress = ($start + $batch_size) / $total_posts * 100;
$next_start = $start + $batch_size;
// Save the status (progress and start)
set_transient('article_rewriter_status', ['start' => $next_start,
'is_running' => true, 'batch_size' => 10]);
// Output the progress bar and status via JavaScript
echo "<script>
document.getElementById('progress-bar').style.width = '" . $progress
. "%';
document.getElementById('progress-status').innerHTML = 'Rewriting job posts... " . ($start + $batch_size) . " of $total_posts';
</script>";
// Flush output and wait for the next batch
flush();
ob_flush();
// Display the updated posts with changes
echo "<script>";
$post_list_html = '';
foreach ($updated_posts as $updated_post) {
$post_list_html .= '<li>';
$post_list_html .= 'Post ID: ' . $updated_post['ID'] . ' - ';
$post_list_html .= 'Title: <b>' . $updated_post['original_title'] . '</b>
→ <i>' . $updated_post['new_title'] . '</i><br>';
$post_list_html .= 'Content Changes: <br>';
$post_list_html .= 'Original: <i>' .
substr($updated_post['original_content'], 0, 100) . '...</i><br>';
$post_list_html .= 'Rewritten: <i>' .
substr($updated_post['new_content'], 0, 100) . '...</i><br>';
$post_list_html .= 'Link: <a href="' . $updated_post['link'] . '"
target="_blank">View Post</a>';
$post_list_html .= '</li>';
}
echo "document.getElementById('post-list').innerHTML = '" . addslashes($post_list_html) . "';";
echo "</script>";
// If we haven't processed all posts, schedule the next batch
if (($start + $batch_size) < $total_posts) {
// Redirect to trigger the next batch
echo "<script>setTimeout(function() { location.href = '" . admin_url('admin.php?page=article_rewriter') . "&start=" . $next_start . "'; },
1000);</script>";
} else {
// Completed all posts
echo "<p>Rewriting process completed for all posts!</p>";
}
} else {
// No more posts to rewrite
echo "<p>No job posts found to rewrite.</p>";
}
}
// Function to call the AI Studio API for rewriting content
function call_ai_rewrite_api($text) {
// Define the API endpoint and your API key (you can replace these with actual values)
$api_url = 'https://aistudio.google.com/app/apikey'; // Replace with actual endpoint if different
// Your actual API key
$api_key = 'AxxxxxxxxxxA'; // Your API key
// Prepare data for API request
$data = [
'text' => $text,
'apikey' => $api_key // Send the API key along with the text to the AI service
];
// Use WordPress HTTP API to make the POST request
$response = wp_remote_post($api_url, [
'method' => 'POST',
'body' => json_encode($data),
'headers' => [
'Content-Type' => 'application/json'
]
]);
// Check if the request was successful
if (is_wp_error($response)) {
return ''; // Return an empty string if there was an error
}
// Parse the response
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Return the rewritten text from the API response
if (isset($data['rewritten_text'])) {
return $data['rewritten_text']; // Return the rewritten content
}
// In case of failure, return the original text
return $text; // Return original content if the API does not return a rewritten version
}
// List processed posts in the admin page
function article_rewriter_list_processed_jobs() {
$processed_posts = get_transient('article_rewritten_posts');
if (empty($processed_posts)) {
echo "<tr><td colspan='4'>No posts have been processed yet.</td></tr>";
} else {
foreach ($processed_posts as $post_id) {
$post = get_post($post_id);
echo "<tr>
<td>" . $post->ID . "</td>
<td>" . $post->post_title . "</td>
<td>Rewritten</td>
<td>" . $post->post_date . "</td>
</tr>";
}
}
}
// Function to get content changes (example: a simple diff)
function get_content_changes($original_content, $new_content) {
// Here, you could implement a proper diffing mechanism or logic
// For simplicity, we'll show the text difference (basic example)
return [
'Original: ' . substr($original_content, 0, 100), // Show the first 100 characters
'Rewritten: ' . substr($new_content, 0, 100)
];
}
?>
i tried to make the given code above
calolina lindas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.