Skip to content

Instantly share code, notes, and snippets.

@salvatorecapolupo
Last active March 29, 2026 08:56
Show Gist options
  • Select an option

  • Save salvatorecapolupo/09817b841c838b8be40c6a31d4cfde10 to your computer and use it in GitHub Desktop.

Select an option

Save salvatorecapolupo/09817b841c838b8be40c6a31d4cfde10 to your computer and use it in GitHub Desktop.
A lightweight Python script to randomly republish old WordPress posts.
import requests
import random
from datetime import datetime
from requests.auth import HTTPBasicAuth
from datetime import datetime, timezone
# --- CONFIGURAZIONE ---
WP_URL = "https://website.tld" # L'URL base del tuo sito (senza /wp-json)
WP_USER = "..." # Il tuo username di WordPress
WP_APP_PASS = "..." # La password applicativa generata (non quella di login!)
API_URL = f"{WP_URL}/wp-json/wp/v2"
def refresh_old_post(post):
"""Aggiorna la data del post esistente ad ADESSO."""
post_id = post['id']
current_title = post['title']['rendered']
# Otteniamo la data e ora attuali in formato ISO 8601
now = datetime.now().replace(microsecond=0).isoformat()
# Genera l'orario UTC attuale nel formato richiesto da WP
now_utc = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S')
# Payload: aggiorniamo la data forzando lo standard UTC
update_data = {
'date': now_utc,
'date_gmt': now_utc,
'status': 'publish' # Opzionale, ma garantisce che rimanga pubblico
}
try:
# NOTA: Usiamo l'ID specifico nell'URL per modificare QUEL post
endpoint = f"{API_URL}/posts/{post_id}"
response = requests.post(
endpoint,
json=update_data,
auth=HTTPBasicAuth(WP_USER, WP_APP_PASS)
)
response.raise_for_status()
print(f"✅ Fatto! Articolo aggiornato con successo.")
print(f"Titolo: {current_title}")
print(f"Nuova Data: {now}")
print(f"Link (invariato): {post['link']}")
except requests.exceptions.RequestException as e:
print(f"❌ Errore durante l'aggiornamento: {e}")
if response is not None:
print(f"Risposta server: {response.text}")
def main():
num = random.uniform(0, 100)
if num <= 1:
print ("no: ", num)
return
print("--- Script Ripubblicazione WP (No Duplicati) ---")
# 1. Recupero
# posts = get_last_100_posts()
posts = get_all_posts()
if not posts: return
valid_posts = posts
if not valid_posts:
print("Nessun articolo valido trovato.")
return
# 3. Scelta Random
chosen_post = random.choice(valid_posts)
print(f"Scelto ID {chosen_post['id']}: '{chosen_post['title']['rendered']}'")
print(f"Data originale: {chosen_post['date']}")
# 4. Aggiornamento data (Ripubblicazione)
refresh_old_post(chosen_post)
def get_all_posts(category_id=7):
"""Recupera TUTTI gli articoli pubblicati."""
posts = []
page = 1
try:
while True:
endpoint = f"{API_URL}/posts?per_page=100&page={page}&status=publish"
if category_id:
endpoint += f"&categories={category_id}"
response = requests.get(endpoint)
if response.status_code == 400:
break # Fine pagine
response.raise_for_status()
data = response.json()
if not data:
break
posts.extend(data)
page += 1
return posts
except requests.exceptions.RequestException as e:
print(f"Errore recupero articoli: {e}")
return []
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment