python 操作wordpress数据库_Python操作WordPress数据库发布文章

使用Python给Wordpress发布文章,我们可以通过两种方式实现:

1、通过xmlrpc,详细操作可以看这里

2、直接操作数据库。

其实大多数情况下,使用第一种方法就可以满足需求了,可是有时候xmlrpc却无法满足我们的需要,比如我之前就遇到过:网站中安装了WP Job Manager插件,发布的文章类型变成了“job_listing”,写入数据的时候,job_listing_category和location这两个字段总是无法成功写入数据。所以,自己今天又研究了一下python直接操作Wordpress数据库发布文章的功能。由于自己对SQL语法不熟悉,花了我大半天时间才折腾成功。

一、建立虚拟环境

virtualenv wp_database

cd wp_database/Scripts

activate

需要安装的库:

mysqlclient==1.4.2.post1

二、查询数据库

代码如下:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import MySQLdb

# 连接数据库

db = MySQLdb.connect("localhost", "root", "", "01py", charset='utf8' )

cursor = db.cursor()

# SQL

sql = "SELECT * FROM wp_posts WHERE post_author =1"

try:

# Execute the SQL command

cursor.execute(sql)

# Commit your changes in the database

db.commit()

except:

db.rollback()

data = cursor.fetchall()

for row in data:

ID = row[0]

author = row[1]

postdate = row[2]

content = row[4]

title = row[5]

# ´òÓ¡½á¹û

print("ID是:{}\n作者:{}\n发布日期:{}\n标题:{}\n内容是:{}\n ".format(ID,author,postdate,title,content))

db.close()

执行结果:

三、发布文章

最终代码

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import MySQLdb

import time

db = MySQLdb.connect("localhost", "root", "", "01py", charset='utf8' )

cursor = db.cursor()

#数据来源

post_content = "python这是文章内容测试"

post_title = "title标题测试New"

post_name = "must_be_only_english"

times=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

# SQL 语句

sql = """INSERT INTO wp_posts(post_author,post_date,post_date_gmt,post_content,post_title,post_excerpt,post_status,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_content_filtered,post_parent,guid,menu_order,post_type,post_mime_type,comment_count)

VALUES ('1','%s','%s','%s','%s','','publish','open','open','','%s','','','%s','%s','','0','http://127.0.0.1/01wp/?p=20','0','post','','0')""" % (str(times),str(times),str(post_content),str(post_title),str(post_name),str(times),str(times))

try:

# Execute the SQL command

cursor.execute(sql)

# Commit your changes in the database

db.commit()

post_id = cursor.lastrowid

if post_id >0:

print("成功插入数据,数据编号为{}".format(post_id))

except:

db.rollback()

db.close()

效果展示:

需要解决的问题:发布的文章“分类目录”那一栏是空的。

看了一下,wordpress的分类目录牵涉到下面两个表:

wp_terms:存储每个目录、标签

wp_term_relationships:存储每个文章、链接和对应分类的关系

所以如果要将上面的代码用于项目的话,还需要继续完善。

原载:蜗牛博客

网址:http://www.snailtoday.com

尊重版权,转载时务必以链接形式注明作者和原始出处及本声明。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值