- def make_post(the_title, the_text, your_user, your_password, your_site, wordpress_category):
- import requests
- import base64
-
- your_credentials = your_user + ":" + your_password
- your_token = base64.b64encode(your_credentials.encode())
- your_header = {'Authorization': 'Basic ' + your_token.decode('utf-8')}
-
- api_url = your_site + '/wp-json/wp/v2/posts'
-
- if not wordpress_category == "":
- # Get the category ID for 'news'
- category_id = get_category_id('news', your_site, your_header)
-
- data = {
- 'title': the_title,
- 'status': 'publish',
- 'content': the_text,
- 'categories': [category_id],
- }
- else:
- data = {
- 'title': the_title,
- 'status': 'publish',
- 'content': the_text,
- }
-
- response = requests.post(api_url, headers=your_header, json=data)
- return response.json()
- def get_category_id(category_name, your_site, your_header):
- api_url = your_site + '/wp-json/wp/v2/categories'
- response = requests.get(api_url, headers=your_header)
-
- categories = response.json()
- for category in categories:
- if category['news'].lower() == category_name.lower():
- return category['id']
-
- return None
复制代码
引入了一个新函数get_category_id来根据类别名称检索类别 ID
该函数向 WordPress API 的/wp-json/wp/v2/categories端点发出 GET 请求以获取类别列表,
然后按名称搜索所需的类别。如果找到,则返回类别 ID
现在可以将类别名称“news”传递给该make_post函数,它将将该帖子分配给“news”类别 |