1. 首页
  2. 工具软件

通过python使用wordpress的api接口写入文章

第一种方法 直接操作数据库

第二种方法 使用wordpress的rest api

官方文档developer.wordpress.org/rest-api/

下面介绍第二种方法:

先试一下api的威力 格式为:

http://{域名}/index.php/wp-json/wp/v2/posts
复制代码

比如:

www.jhcms.net/index.php/w…

如何创建一个新文章

官方文档 developer.wordpress.org/rest-api/re…

得到重要信息如下:

参数

date The date the object was published, in the site’s timezone.
date_gmt The date the object was published, as GMT.
slug An alphanumeric identifier for the object unique to its type.
status A named status for the object. One of: publishfuturedraftpendingprivate
password A password to protect access to the content and excerpt.
title The title for the object.
content The content for the object.
author The ID for the author of the object.
excerpt The excerpt for the object.
featured_media The ID of the featured media for the object.
comment_status Whether or not comments are open on the object. One of: openclosed
ping_status Whether or not the object can be pinged. One of: openclosed
format The format for the object. One of: standardasidechatgallerylinkimagequotestatusvideoaudio
meta Meta fields.
sticky Whether or not the object should be treated as sticky.
template The theme file to use to display the object. One of:“
categories The terms assigned to the object in the category taxonomy.
tags The terms assigned to the object in the post_tag taxonomy.

定义#Definition

POST /wp/v2/posts 意为要用post方法提交到 /wp/v2/posts这个地址

默认是只读api要实现提交数据需要安装插件jwt,安装了jwt后可以请求到token了,在rest api中传入token信息,系统就不会拒绝你的发布文章的操作了

操作步骤

  1. 第一步 在wordpress管理后台安装 JWT Auth 插件

  2. 第二部 在网站根目录 .htaccess 文件中添加如下内容

    RewriteEngine on
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
    
    SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
    复制代码
  3. 在 wp-config.php 文件中添加如下内容:

    define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');//随便填写一个密码
    define('JWT_AUTH_CORS_ENABLE', true);
    复制代码
  4. Post请求调用http://{你的域名}/wp-json/jwt-auth/v1/token接口获取token

  5. 根据token进行文章的发布

核心代码如下:

# -*- coding:utf-8 -*-
import re
import requests
import json
import time
from numpy import *




def get_token():
    session = requests.Session()
    url = 'http://sex.newban.cn/wp-json/jwt-auth/v1/token'
    data = {
        'username':"son3g",
        'password':"123456"
        }
    headers = {'user-agent': 'Mozolla/5.0',
               }
    resp = session.post(url, data=data, headers=headers, timeout=3335)  # 请求
    r = json.loads(resp.content)
    return r




def _do_post( token =''):
        session = requests.Session()
        url = 'http://sex.newban.cn/wp-json/wp/v2/posts'
        data = {
                'date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
                'date_gmt': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()),
                'slug': 'xx',
                'status': 'publish',
                'password': '',
                'title': 'rest api发布post测试',
                'content': '系统测试我想我是海冬天的大海',
                'author	': '121852835@qq.com',
                'excerpt': '',
                'featured_media': '0',
                'comment_status': 'open',
                'ping_status': 'closed',
                'format': 'standard',
                'meta': [],
                'sticky': False,  # 置顶
                'template': '',
                'categories': '1',  # 1 未分类
                'tags': ''
        }
        headers = {'user-agent': 'Mozolla/5.0',
                   'Authorization': 'Bearer ' + token
                   }
        resp = session.post(url, data=data, headers=headers, timeout=3335)  # 请求
        print (resp.text)
        # r = json.loads(resp.content, 'utf-8')

        # if r["code"] == 400:
        #         print r["code"]
        #         print r["message"]
        #         print r["data"]
        #         print r["data"]["status"]
        #
        #
        #         # print r["data"]["params"]
        #         for key in r["data"]["params"]:
        #             print ("%s=> %s" % (key, r["data"]["params"][key]))
        #         # print 'resp.text=>' + resp.text
        #
        #         # print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        #         # print time.strftime('%a, %d %b %Y %H:%M:%S GMT+0800 (CST)',time.localtime(time.time())),
        #         dt = formatdate(None, usegmt=True)
        #         dt1 = formatdate(None, usegmt=False)
        #         dt3 = formatdate()
        #         print(dt)
        #         print(dt1)
        # else:
        #         print r["code"]
        #         print r["message"]
        #         print resp.status_code
if __name__=='__main__':
        r = get_token()
        print (r)
        _do_post(r["data"]['token'])
复制代码

参考:

[如何将python采集到的文章保存到wordpress – 掘金](https://juejin.cn/post/7017693085895229453)

备注说明:

featured_media 这个是媒体id,封面图像;

categories、tags、featured_media 都是数字id,可通过控制台查找;

发表评论

邮箱地址不会被公开。

评论列表(1条)