在本指南中,我們將探索如何使用 WordPress API 進行驗證並安排特定發佈時間的貼文。這些步驟將幫助您以程式設計方式安全地管理您的 WordPress 內容。
要安全地與 WordPress API 交互,您需要對您的要求進行身份驗證。讓我們深入研究兩種常見的方法:
應用程式密碼是 WordPress 中的內建功能,可讓您產生用於 API 存取的安全密碼,而不會洩露您的主帳戶密碼。
使用應用程式密碼:
<p>import requests</p> <p>url = "https://your-wordpress-site.com/wp-json/wp/v2/posts"<br> username = "your_username"<br> app_password = "your_application_password"</p> <p>headers = {<br> "Content-Type": "application/json"<br> }</p> <p>response = requests.get(url, auth=(username, app_password), headers=headers)</p>
對於較舊的 WordPress 版本或如果您喜歡替代方法:
<p>import requests</p> <p>url = "https://your-wordpress-site.com/wp-json/wp/v2/posts"<br> username = "your_username"<br> password = "your_password"</p> <p>headers = {<br> "Content-Type": "application/json"<br> }</p> <p>response = requests.get(url, auth=(username, password), headers=headers)</p>
要安排貼文在特定時間發布,請在建立或更新貼文時使用日期參數。方法如下:
<p>import requests<br> from datetime import datetime, timedelta</p> <p>url = "https://your-wordpress-site.com/wp-json/wp/v2/posts"<br> username = "your_username"<br> app_password = "your_application_password"</p> <p># Schedule the post for 2 days from now at 10:00 AM<br> scheduled_time = datetime.now() + timedelta(days=2)<br> scheduled_time = scheduled_time.replace(hour=10, minute=0, second=0, microsecond=0)<br> scheduled_time_str = scheduled_time.isoformat()</p> <p>data = {<br> "title": "Scheduled Post Example",<br> "content": "This is the content of the scheduled post.",<br> "status": "future",<br> "date": scheduled_time_str<br> }</p> <p>response = requests.post(url, auth=(username, app_password), json=data)</p> <p>if response.status_code == 201:<br> print("Post scheduled successfully!")<br> else:<br> print("Error scheduling post:", response.text)</p>
要重新安排現有帖子,您需要其帖子 ID:
<p>import requests<br> from datetime import datetime, timedelta</p> <p>post_id = 123 # Replace with the actual post ID<br> url = f"https://your-wordpress-site.com/wp-json/wp/v2/posts/{post_id}"<br> username = "your_username"<br> app_password = "your_application_password"</p> <p># Reschedule the post for 1 week from now at 2:00 PM<br> new_scheduled_time = datetime.now() + timedelta(weeks=1)<br> new_scheduled_time = new_scheduled_time.replace(hour=14, minute=0, second=0, microsecond=0)<br> new_scheduled_time_str = new_scheduled_time.isoformat()</p> <p>data = {<br> "status": "future",<br> "date": new_scheduled_time_str<br> }</p> <p>response = requests.post(url, auth=(username, app_password), json=data)</p> <p>if response.status_code == 200:<br> print("Post rescheduled successfully!")<br> else:<br> print("Error rescheduling post:", response.text)</p>
透過遵循本指南,您應該能夠使用 WordPress API 進行身份驗證,並以程式設計方式安排特定發佈時間的貼文。
引用:
以上是使用 WordPress API 的綜合指南:身份驗證和後期調度的詳細內容。更多資訊請關注PHP中文網其他相關文章!