
Instruction:
Create a ~1500-character Google My Business post from this URL:
{URL}.
Audience: beginners/intermediate devs.
Focus: Explain ONE core outcome, include 1 tiny code line (no long blocks), and end BEFORE 1500 chars.
Tone: clear, helpful, no hype. Avoid keyword stuffing.
CTA:
“Read the full tutorial:
{URL}”
This script is divided into two parts for better clarity and modularity.
In Part I, we define a list of technical topics (keywords), randomly select one, and insert it into a well-crafted prompt template using str_ireplace(). This prepares a complete prompt that could be sent to an AI model for content generation.
In Part II, the script connects to Google’s Gemini API using a secure API key. It sends the generated prompt to the model and retrieves the AI-generated social media content in response.
This two-step approach makes it easy to reuse or test the prompt independently before invoking the API.
<?php
/**
* Practical use of str_ireplace():
* Pick a random keyword from an array, inject into a prompt paragraph,
* and (optionally) call your AI API to generate a social media post.
*/
// 1) Your keyword pool (expand as needed)
$keywords = [
'Tkinter Treeview insert',
'tkcalendar DateEntry',
'PHP array unpacking',
'MySQL BETWEEN query',
'Regex with preg_match',
'Python file handling',
];
// 2) Prompt paragraph template
$promptTemplate = <<<TXT
Create a ~1500-character Google My Business post on: {KEYWORD}.
Audience: beginners/intermediate devs.
Focus: Explain ONE core outcome, include 1 tiny code line (no long blocks), and end BEFORE 1500 chars.
Tone: clear, helpful, no hype. Avoid keyword stuffing.
TXT;
// 3) Pick a random keyword
if (empty($keywords)) {
die("No keywords available.\n");
}
$randomKey = array_rand($keywords);
$selected = $keywords[$randomKey];
// 4) Replace placeholder with keyword
$replacedCount = 0;
$finalPrompt = str_ireplace('{KEYWORD}', $selected, $promptTemplate, $replacedCount);
// 5) Output prompt
header('Content-Type: text/plain; charset=UTF-8');
echo "Selected keyword: {$selected}\n";
echo "Occurrences replaced: {$replacedCount}\n\n";
echo "---- PROMPT TO SEND ----\n";
echo $finalPrompt . "\n";
// -------------------- Optional Gemini API Call ( Part - II )--------------------
require 'ai_v1/settings.php'; // defines $GOOGLE_API_KEY
$MODEL = 'gemini-2.5-flash';
if (!$GOOGLE_API_KEY) {
exit("\n[Note] Skipping API call: set GEMINI_API_KEY env var.\n");
}
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$MODEL}:generateContent";
$payload = [
"contents" => [[ "parts" => [["text" => $finalPrompt]] ]]
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"x-goog-api-key: $GOOGLE_API_KEY",
],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 60,
]);
$res = curl_exec($ch);
if (curl_errno($ch)) {
echo "\nAPI error: " . curl_error($ch) . "\n";
} else {
$data = json_decode($res, true);
$text = $data['candidates'][0]['content']['parts'][0]['text'] ?? null;
echo "\n---- GENERATED SOCIAL POST ----\n";
echo $text ? $text : "No text returned. Raw response:\n" . $res;
}
curl_close($ch);
?>
Use the following concepts and examples to expand this tutorial further — targeting different platforms, post formats, and creative ideas. Build your own workflows that generate unique posts for LinkedIn, Twitter, Instagram, or Google Business directly from URLs or content snippets.
Provide short, tuned templates per platform + audience. Inject {URL}, {AUDIENCE}, {TONE}, {CTA} as variables.
// Twitter/X (≤280 chars)
"Write a concise post (≤250 chars) for {AUDIENCE} about {URL}. Tone: {TONE}.
End with 1 hashtag and a short CTA."
// LinkedIn (~600–1200 chars)
"Write a clear LinkedIn post for {AUDIENCE} summarizing {URL}.
Focus on one outcome, add 1 question to invite comments, end with a soft CTA."
// Instagram caption
"Create an IG caption (≤150 words) based on {URL}. Conversational.
One key benefit, one micro-tip, 3 relevant hashtags, 1 CTA."
// Google Business Profile (~1200–1500 chars)
"Create a GBP post from {URL}. Audience: beginners/intermediate devs.
One core outcome, include 1 tiny code line (no long blocks), end with CTA link."
Collect URLs (CSV/array), fetch basic context (title, meta description, first 120–200 words), then feed to the model.
<?php
$urls = [
"https://example.com/post-1",
"https://example.com/post-2",
"https://example.com/post-3"
];
function fetch_context($url) {
$html = @file_get_contents($url);
if(!$html) return ["title"=>"", "desc"=>"", "snippet"=>""];
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$title = $xpath->evaluate('string(//title)');
$desc = $xpath->evaluate('string(//meta[@name="description"]/@content)');
$text = trim($xpath->evaluate('string(//body)'));
$snippet = mb_substr(preg_replace("/\s+/", " ", $text), 0, 600);
return ["title"=>$title, "desc"=>$desc, "snippet"=>$snippet];
}
$chosen = $urls[array_rand($urls)];
$ctx = fetch_context($chosen);
// Build prompt (example: LinkedIn)
$prompt = "Create a LinkedIn post for intermediate devs. Base it on: {$chosen}\n".
"Title: {$ctx['title']}\nMeta: {$ctx['desc']}\nSnippet: {$ctx['snippet']}\n".
"One key outcome, 1 question, end with CTA linking to {$chosen}.";
?>
Tip: Cache fetch_context() results (filesystem/Redis) to save API calls while iterating.
// Weak
"Write a post about this link {URL}."
// Strong
"Write a {PLATFORM} post for {AUDIENCE} based on {URL}. Highlight ONE benefit,
keep it under {LIMIT}. Include 1 question for engagement and end with CTA:
<a href='{URL}'>Read more</a>."
/app
/config.php // env, model, limits
/helpers.php // fetch_context(), sanitize(), cache_get/set()
/ai_client.php // call_gemini($prompt)
/render.php // HTML render + UI
/publishers/*.php // X, LinkedIn, GBP schedulers
Let a user paste URLs or upload CSV, pick platform + tone, then generate.
<form method="post">
<textarea name="urls" placeholder="One URL per line" required></textarea>
<select name="platform">
<option>Twitter</option><option>LinkedIn</option>
<option>Instagram</option><option>GBP</option>
</select>
<input name="tone" placeholder="Tone e.g., helpful, witty">
<button>Generate</button>
</form>
After approval, queue for APIs (X, LinkedIn) or use schedulers (Buffer/Hootsuite). Respect rate limits; keep retry logic.
Add a lang selector; pass language + locale to the prompt; enforce local character conventions.
"Write in {LANGUAGE_CODE}. Use local punctuation and spacing rules."
plus2net/ai-social-posts.fetchContext(), buildPrompt(), callModel(), validatePost(), publish().Generate a post when a blog is published. Add meta-box to preview/edit before scheduling.
add_action('publish_post', function($post_id){
$url = get_permalink($post_id);
$ctx = fetch_context($url);
$prompt = build_prompt($url, $ctx, 'LinkedIn');
$post = call_model($prompt);
update_post_meta($post_id, '_generated_social_post', $post);
});
<?php
require __DIR__.'/vendor/autoload.php'; // if needed
$urls = array_filter(array_map('trim', explode("\n", $_POST['urls'] ?? '')));
$platform = $_POST['platform'] ?? 'LinkedIn';
$tone = $_POST['tone'] ?? 'helpful';
function fetch_context($url){ /* same as above (trimmed for brevity) */ }
function validate_post($text, $url){
return [
'has_url' => str_contains($text, $url),
'has_cta' => preg_match('/read|learn|try|start|join|visit/i', $text) === 1,
'len_ok' => mb_strlen($text) < 1200
];
}
if($_SERVER['REQUEST_METHOD']==='POST' && $urls){
$picked = $urls[array_rand($urls)];
$ctx = fetch_context($picked);
$prompt = "Platform: {$platform}\nTone: {$tone}\nURL: {$picked}\n".
"Title: {$ctx['title']}\nMeta: {$ctx['desc']}\n".
"Snippet: {$ctx['snippet']}\n".
"Write ONE {$platform} post with 1 outcome and a CTA linking to {$picked}.";
$generated = call_gemini($prompt); // your existing client
$check = validate_post($generated, $picked);
}
?>
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.