在本指南中,我们将探索如何使用 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中文网其他相关文章!