import requests
from datetime import datetime, timedelta
# Step 1: Set API credentials
api_url = "api_url = "https://example.com/wp-json/wp/v2"" # Replace with the correct URL
username = "login"
password = "pass"
# Function to download all posts (taking pagination into account)
def get_all_draft_posts(api_url, auth):
page = 1
all_posts = []
while True:
response = requests.get(f"{api_url}/posts", params={"status": "draft", "page": page, "per_page": 100},
auth=auth)
if response.status_code == 200:
posts = response.json()
if not posts:
break
all_posts.extend(posts)
page += 1
else:
print(f"Error: {response.status_code}")
break
return all_posts
# Step 2: Get a list of posts with 'draft' status
auth = (username, password)
posts = get_all_draft_posts(api_url, auth)
# Step 3: Update post publication dates
if posts:
# Set start_date to the beginning of the next day
now = datetime.now()
start_date = datetime(now.year, now.month, now.day) + timedelta(days=1)
for i, post in enumerate(posts):
# Set the publication time to 9:00 a.m. or 3:00 p.m.
hour_of_publication = 9 if i % 2 == 0 else 15
new_date = (start_date + timedelta(days=i // 2)).replace(hour=hour_of_publication, minute=0, second=0)
post_id = post['id']
data_to_update = {
"date": new_date.strftime('%Y-%m-%dT%H:%M:%S'),
"status": "publish"
}
response = requests.post(f"{api_url}/posts/{post_id}", json=data_to_update, auth=auth)
if response.status_code == 200:
print(f"Post ID {post_id} updated {new_date}")
else:
print(f"Post ID update error {post_id}: {response.status_code}")
else:
print("No posts to update.")