[WordPress] 글쓰기 API 사용하기
Hits: 310
ChatGPT를 통해서 글을 작성하기 위해 워드프레스의 API 사용법을 찾아보았다.
Python을 이용하여 글을 작성하는 코드를 만들었고 해당 내용은 다음과 같다.
import json
import requests
from urllib.parse import urljoin
WP_URL = 'https://www.leesowoon.com/' #자신의 워드프레스 주소
WP_USERNAME = 'username' # 사용자이름
WP_PASSWORD = 'application password' #어플리케이션 비밀번호 #사용자 비밀번호가 아님
status = 'publish' #즉시발행:publish, 임시저장:draft
title = '포스팅 테스트' #글의 제목
content = f'''
<br>
<h3>어떻게 글이 써지는지 테스트하기기</h3>
<br>
'''
category_ids = [43]
tag_ids = [2]
user_ = WP_USERNAME
pass_ = WP_PASSWORD
payload = {"status": status,
"title": title,
"content": content,
"categories": category_ids
}
#if media_id is not None:
# payload['featured_media'] = media_id
res = requests.post(urljoin(WP_URL, "wp-json/wp/v2/posts"),
data=json.dumps(payload),
headers={'Content-type': "application/json"},
auth=(user_, pass_))
if res.ok:
print(f"성공 code:{res.status_code}")
else:
print(f"실패 code:{res.status_code} reason:{res.reason} msg:{res.text}")
내용을 설명하면 다음과 같다.
WP_URL | 현재 워드프레스 주소 https까지 붙이기 |
WP_USERNAME | 워드프레스 사용자 ID(글쓴이 or 관리자 권한 필수) |
WP_PASSWORD | 사용자에 들어가면 새 응용 프로그램 이름의 비밀번호를 입력(아래 캡처 참고) |
status | 즉시 발행(publish), 임시 글쓰기(draft) 선택 |
title | 글 제목 |
content | 글 내용 <h3>, <br> 등등 html 코드가 들어가야함 |
category_ids | 어떤 카테고리에 글을 작성할지 id 값 입력(아래 url 주소에 있는 숫자 확인하기) |
tag_ids | 어떤 태그를 추가할지 id 값 입력( 아래 url 주소에 있는 숫자 확인하기) |


category_ids에 위 숫자(43) 입력

tag_ids에 위 숫자(35) 입력
아래는 코드를 실행했을 때 작성된 글이다.

작성해놓은 코드 복사해서 값만 바꿔주면 글쓰기 되는것을 확인할 수 있을 것이다.
테스트를 진행하며 삽질했던 내용…
필자의 경우 AWS의 Lightsail을 사용하여 WordPress를 사용중인데
도메인 처리, https 문제로 생각보다 많이 시간을 낭비하였다.
내가 겪은 상황은 다음과 같다.
- 401 error가 지속적으로 나왔다.
- 나는 처음에 user의 password를 입력해야하는줄 알았는데 아니었다. 사용자에 새 응용 프로그램을 추가하고 그 비밀번호를 입력하여야만 정상적으로 응답이 오는것 같았다.
- 하지만 글은 써지지 않았다.
- ssl이 설정이 안되어있어 http로 글쓰기를 요청하였었다.
- https://docs.aws.amazon.com/ko_kr/lightsail/latest/userguide/amazon-lightsail-enabling-https-on-wordpress.html 참고하여 https 활성화 완료
- 이 https 활성화하는 과정에서도 오류가 계속 났었는데
- route53에 www.leesowoon.com에 대한 정보가 등록이 안되어있어 계속 오류가 났었다.
- leesowoon.com처럼 동일하게 A 레코드를 등록해주니 https 활성이 완료되었다.
- ssl 설정 이후 https로 wordpress 글쓰기 api를 요청하였으나 등록이 되지 않았다.
- 지속적으로 200 ok는 떨어지고 있었고 response.text를 보아도 get방식과 동일한 모든 글만 나올 뿐이었다.
- 워드프레스 주소를 https://leesowoon.com으로 테스트를 진행했었는데 https://www.leesowoon.com으로 하니 201 ok가 나오는것을 확인하였다.
- 아마 lightsail에서 https 설정하는 과정에서 변경된건지 wordpress 설정에서 www.leesowoon.com을 설정해놓은게 있는게 아닐까 싶다(정확한 원인을 찾아보진않음)
두서없이 적긴했으나 API를 사용하면서 내 경험담이 도움이 되었으면 좋겠다.
댓글 2개
SEO Backlink Services
Thanks for one’s marvelous posting! I quite enjoyed reading it,
you might be a great author. I will always bookmark your blog and may come back down the road.
I want to encourage you to ultimately continue your great writing, have a nice evening!
SeoBests.com
Right here is the perfect blog for anyone who really wants to understand this topic.
You understand so much its almost hard to argue with you (not that I actually will need to…HaHa).
You definitely put a brand new spin on a topic that has been discussed for a long time.
Great stuff, just great!