今天介紹的是一些通過代碼編寫,在WordPress博客里添加各種數(shù)據(jù)(比如日志、評論、分類等)的簡單方法。
在WordPress里插入一篇文章非常簡單。要用到的是wp_insert_post()函數(shù),這個函數(shù)以數(shù)組作為參數(shù)。
如果你想試驗一下這個函數(shù),可以把下面的代碼復制到functions.php文件。
global $user_ID;$new_post = array( 'post_title' => 'My New Post', 'post_content' => 'Lorem ipsum dolor sit amet...', 'post_status' => 'publish', 'post_date' => date('Y-m-d H:i:s'), 'post_author' => $user_ID, 'post_type' => 'post', 'post_category' => array(0));$post_id = wp_insert_post($new_post);
$new_post數(shù)組里的參數(shù)包括:
在WordPress里插入評論也相當容易。同樣是把下面的代碼復制到functions.php文件。
$data = array( 'comment_post_ID' => 1, 'comment_author' => 'admin', 'comment_author_email' => 'admin@admin.com', 'comment_author_url' => 'http://www.catswhocode.com', 'comment_content' => 'Lorem ipsum dolor sit amet...', 'comment_author_IP' => '127.0.0.1', 'comment_agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; fr; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3', 'comment_date' => date('Y-m-d H:i:s'), 'comment_date_gmt' => date('Y-m-d H:i:s'), 'comment_approved' => 1,);$comment_id = wp_insert_comment($data);
wp_insert_comment()函數(shù)和wp_insert_post()一樣,也是以數(shù)組作為參數(shù):
WordPress的內(nèi)置函數(shù)wp_set_object_terms()可以將文章添加到各分類中。
我們需要做的就是創(chuàng)建一個數(shù)組,數(shù)組里包含需要添加的分類ID,然后:
$category_ids = array(4, 5, 6);wp_set_object_terms( $post_id, $category_ids, 'category');
wp_set_object_terms()用了三個參數(shù):文章ID, 分類ID的數(shù)組、分類類型(此處為"category")
添加標簽甚至不需要用到新函數(shù),wp_set_object_terms()函數(shù)同樣可以實現(xiàn)添加標簽的效果。
$tag_ids = array(7, 8, 9);wp_set_object_terms( $post_id, $tag_ids, 'post_tag');
在文章發(fā)表時自動生成自定義字段會為我們節(jié)省很多時間。
依然是把下面的代碼復制到functions.php文件,然后發(fā)表新文章時,就會有自動生成的自定義字段了。
function add_custom_field_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { add_post_meta($post_ID, 'field-name', 'custom value', true); }}add_action('publish_page', 'add_custom_field_automatically');add_action('publish_post', 'add_custom_field_automatically');
原理:首先生成一個函數(shù)。該函數(shù)用以確認新發(fā)表文章不是某篇舊文的修改版,然后添加一個自定義字段,字段名為field-name,字段值為custom value。之后,調(diào)用一個hook來確保每當新文章或者新頁面發(fā)布時都會調(diào)用add_custom_field_automatically()函數(shù)。