wordpress提供了豐富的xmlrpc接口api來供我們遠程操控wp的內容。偉大的開源社區有人就將這些api做了一下封裝,提供了一個功能比較完整的python庫,庫的使用文檔地址http://python-wordpress-xmlrpc.readthedocs.org/ , 文檔內容還是很全面的。這里我將自己試驗的一些內容做一下總結。
wordpress有一個revision的機制,導致我們在通過api接口更新文檔時,會在數據庫中保存2條記錄,一條是正文,另外一條 id-revision之類的記錄,對我來說沒什么用,所以先通過代碼禁用掉。
define('WP_POST_REVISIONS', false);
在這個python類庫中,WordPressPost對象的屬性通過setattr來實現的。
查詢Post
利用api可以獲取指定的post的相關信息,具體有哪些信息可以參看下面新增post的那個表。一個簡單的獲取post列表的代碼例子如下:
def TestGetPost(): wp = wp_server.call(wordpress_xmlrpc.methods.posts.GetPosts()) for w in wp: print w.title print w.post_status
此外,GetPosts函數接受不同的參數來進行條件查詢, 例如下面的的語句返回最近更新的100個post
recently_modified = client.call(posts.GetPosts({'orderby': 'post_modified', 'number': 100}))
下面的代碼是返回從offset開始的指定條數的post條目:
posts = client.call(posts.GetPosts({'number': increment, 'offset': offset}))
新建Post
新建的post公國wordpress_xmlrpc.methods.posts.NewPost(WordPressPost)來創建,以下是一個簡短的新建一個Post的代碼段。
post = WordPressPost() post.title = "test4" post.date_modified = datetime.datetime.now() post.content = "全英文界面,但有非官方的中文翻譯。推薦直接閱讀英語原文,既准確可靠又可提高英語水平。做題方式模擬正式比賽,采用標准測評機、文件輸入輸出、直接提交程序源文件的測評方式。" post.excerpt = "全英文界面,但有非官方的中文翻譯" post.post_status = "publish" print wp_server.call( wordpress_xmlrpc.methods.posts.NewPost(post))
插入時支持的參數有:
python中字段 | xmlrpc對應字段 | 含義 |
date | post_date_gmt | |
date_modified | post_modified_gmt | post的修改時間 |
slug | post_name | |
post_status | post_status | post的狀態, 可選draft、publish,常用publish就可以直接發布post了 |
title | post標題 | |
content | post_content | post 內容 |
excerpt | post_excerpt | 摘要 |
link | ||
comment_status | ||
ping_status | ||
terms | ||
terms_names | ||
custom_fields | ||
enclosure | ||
post_format | ||
thumbnail | post_thumbnail | |
sticky | 置頂顯示, 設置True | |
post_type | post的類型, 默認為post, 也可以為page, | |
parent_id | post_parent | 上級文章的id |
menu_order | ||
guid | ||
mime_type | post_mime_type |
設置post的category和tag, Post的terms屬性對應 WordPressTerm 對象。如果要新增一個term,可以用下面的代碼來進行
post = WordPressPost() post.title = 'Post with new tags' post.content = '...' post.terms_names = { 'post_tag': ['tagA', 'another tag'], 'category': ['My Child Category'], } post.id = client.call(posts.NewPost(post))
編輯Post
編輯已經發布的Post,和新建基本上一樣, 還是依賴於WordPressPost結構類
def TestModifyPost(): wp = wp_server.call(wordpress_xmlrpc.methods.posts.GetPost(1)) wp.sticky = True print wp_server.call(wordpress_xmlrpc.methods.posts.EditPost(wp.id, wp))
上面的代碼將postid是1的post進行置頂顯示。