通过api可以让开发人员通过程序创建文章。

第一步:开启应用密码

要使用rest api,需要使用https部署的域名。

但是我们测试环境是ip形式的,就没有域名,更没有https。
这时可以在wp-config.php中添加define( 'WP_ENVIRONMENT_TYPE', 'local' ); 来开启应用密码。

去用户 - 所有用户中,编辑一个用户,往下找,可以看到应用密码。给他配置一下。

第二步:使用代码调用

python 示例代码

import requests
import base64
from datetime import datetime

wp_base_path = "http://your_host"
username = "admin"
password = "YOUR_APPLICATION_PASSWORD"
credentials = username + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
print('header', header)

# 访问rest api报404时
# https://blog.csdn.net/weixin_44440133/article/details/135074412


def get_posts():
    url = wp_base_path + "/wp-json/wp/v2/posts"
    response = requests.get(url, headers=header)
    print(response.status_code)
    json_obj = response.json() #json.dump()
    print(json_obj)


# 提交文章
# https://developer.wordpress.org/rest-api/reference/posts/
def new_post(title, content, category_array):
    url = wp_base_path + "/wp-json/wp/v2/posts"

    formatted_time = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
    post = {
        'title': title,
        # 状态
        'status': 'publish',
        'content': content,
        'date_gmt': formatted_time,
        'categories': category_array
    }
    response = requests.post(url, headers=header, json=post, verify=True)
    print(response.status_code)
    if response.status_code == 201:
        return True
    else:
        return False


if __name__ == "__main__":
    # get_posts()
    with open('index.txt', 'r') as f:
        lines = f.readlines()
        post_content = ''.join(lines)
    new_post("test title3", post_content, [15, 16])

java 示例代码(部分)


    private static final String wp_base_path = "http://your_host";
    private static final String username = "admin";
    private static final String password = "YOUR_APPLICATION_PASSWORD";
    private static final String credentials = username + ':' + password;
    
    public boolean newPost(String lastFileUrl, WxmpArticleImagePersist p) {
        String content = buildContent(lastFileUrl);
        if (StringUtils.isBlank(content)) {
            return false;
        }
        byte[] credentialsBytes = credentials.getBytes(StandardCharsets.US_ASCII);
        byte[] encodeBase64 = Base64.encodeBase64(credentialsBytes);
        String token = new String(encodeBase64, StandardCharsets.UTF_8);
        Map<String, String> headers = Map.of("Authorization", "Basic " + token);

        final String restUrl = wp_base_path + "/wp-json/wp/v2/posts";

        String formattedTime = DateUtils.formatDatetimeToday();
        String title = "无标题-" + formattedTime;
        if (Objects.nonNull(p)) {
            title = p.getTitle();
        }
        Map<String, Object> payload = new HashMap<>();
        payload.put("title", title);
        payload.put("status", "publish");
        payload.put("content", content);
        payload.put("date_gmt", formattedTime);
        payload.put("categories", new Integer[]{16, 15});

        String s = HttpClient4Utils.doPostJson(restUrl, payload, null, headers);
        log.info("s={}", s);
        if (StringUtils.containsAny(s, "\"id\":")) {
            return true;
        }
        return false;
    }