最近想學(xué)習(xí)一下 WordPress 自定義文章類型,發(fā)現(xiàn) tutsplus 的文章介紹的挺系統(tǒng),翻譯過來分享下(倡萌英文不太好,只翻譯個意思,還望多包涵,有能力的朋友直接去看英文吧。)
下載本教程演示的文件:http://www.ydqwiac.cn/img/2013/03/Movie-Reviews.zip
WordPress 是專為定制而生的,它的每一個節(jié)都是可定制的。在這篇文章中,我們將探討眾所周知的 WordPress 最強(qiáng)大的功能之一:自定義文章類型(Custom Post Types),這個功能的到來,也意味著WordPress又上了一個新的高度。
到底什么是 自定義文章類型?
假如你想為你的博客添加一個單獨的部分來發(fā)表電影評論。通過使用 自定義文章類型,你可以創(chuàng)建一種新的文章類型,就像文章(posts)和頁面(pages)一樣,它可以包含一組不同的數(shù)據(jù)。比如新的管理菜單、專門的編輯頁面、自定義分類 和 更多實用的發(fā)布管理功能。
自定義文字類型 擁有新的文章管理選項,就像默認(rèn)的文章類型(文章、頁面、附件 )一樣。一種 自定義文章類型 可以存儲各種各樣的信息。它有專門的編輯器、多媒體上傳 并使用WordPress現(xiàn)有的表結(jié)構(gòu),便于數(shù)據(jù)管理。使用 WordPress 的 API 來創(chuàng)建自定義文章類型的主要優(yōu)點在于,它可以很好地兼容現(xiàn)有的主題模板。同時,自定義文章類型也非常符合 SEO,因為它們擁有自己的漂亮的固定鏈接樣式。

為什么使用自定義文章類型?
自定義文章類型幫助我們將不同類型的文章放在不同的容器中,它輕而易舉地將我們的文章和其他的區(qū)別開來。
創(chuàng)建一個自定義文章類型插件
下面我們將創(chuàng)建一個自定義文章類型插件來顯示最喜歡的電影評論,開始吧!
步驟1:創(chuàng)建 WordPress 插件目錄
打開你的WordPress插件目錄/wp-content/plugins,創(chuàng)建一個名為 Movie-Reviews 的新目錄。
步驟2:創(chuàng)建 PHP 文件
打開 Movie-Reviews 目錄,創(chuàng)建一個名為 Movie-Reviews.php 的PHP文件。
步驟3:添加頭部
打開剛才的php文件,在頂部添加下面的代碼:
<?php
/*
Plugin Name: Movie Reviews
Plugin URI: http://wp.tutsplus.com/
Description: Declares a plugin that will create a custom post type displaying movie reviews.
Version: 1.0
Author: Soumitra Chakraborty
Author URI: http://wp.tutsplus.com/
License: GPLv2
*/
?>
步驟4:注冊自定義函數(shù)
在PHP結(jié)束符 ?> 的前面,添加下面的代碼,來確保每次創(chuàng)建新頁面的初始化階段,執(zhí)行自定義函數(shù) create_movie_review 。
add_action( 'init', 'create_movie_review' );
步驟5:添加功能函數(shù)
添加 create_movie_review 函數(shù)的功能代碼:
function create_movie_review() {
register_post_type( 'movie_reviews',
array(
'labels' => array(
'name' => 'Movie Reviews',
'singular_name' => 'Movie Review',
'add_new' => 'Add New',
'add_new_item' => 'Add New Movie Review',
'edit' => 'Edit',
'edit_item' => 'Edit Movie Review',
'new_item' => 'New Movie Review',
'view' => 'View',
'view_item' => 'View Movie Review',
'search_items' => 'Search Movie Reviews',
'not_found' => 'No Movie Reviews found',
'not_found_in_trash' => 'No Movie Reviews found in Trash',
'parent' => 'Parent Movie Review'
),
'public' => true,
'menu_position' => 15,
'supports' => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ),
'taxonomies' => array( '' ),
'menu_icon' => plugins_url( 'images/image.png', __FILE__ ),
'has_archive' => true
)
);
}
這個 register_post_type 函數(shù)對我們最有用,一旦對它發(fā)出聲明,它就為一個新的自定義文章類型準(zhǔn)備好了各種WordPress管理功能。這個函數(shù)包括兩個參數(shù):第一個是定義了自定義文章類型的名字 name,第二個是一個數(shù)組,定義新的自定義文章類型的屬性。
在這里,它的另一個的數(shù)組,包含不同的標(biāo)簽,用來顯示這個自定義文章類型的不同部分,例如 ”name“會在儀表盤中顯示這個自定義文章類型 的名字,”edit“和”view“將顯示”編輯“和”查看“按鈕。其他的也就非常容易理解了。
在接下來的參數(shù):
- ‘public’ => true 決定自定義文章類型在管理后臺和前端的可見性
- ‘menu_position’ => 15 決定自定義文章類型菜單的位置
- ‘supports’ => array( ‘title’, ‘editor’, ‘comments’, ‘thumbnail’, ‘custom-fields’ ) 決定顯示哪些自定義文章類型的功能
- ‘taxonomies’ => array( ” ) 創(chuàng)建自定義分類。在這里沒有定義。
- ‘menu_icon’ => plugins_url( ‘images/image.png’, __FILE__ ) 顯示管理菜單的圖標(biāo)
- ‘has_archive’ => true 啟用自定義文章類型的存檔功能
請訪問 register_post_type 了解更多自定義文章類型的參數(shù)細(xì)節(jié)。
步驟6:自定義文章類型的圖標(biāo)
制作一個 16*16 像素的圖標(biāo),放在當(dāng)前的插件目錄,這是必需的,用來在儀表盤中作為自定義文章類型的圖標(biāo)。
步驟7:啟用這個插件
啟用插件,就看到了一個新的自定義文章類型,它有內(nèi)容編輯器、發(fā)布功能、圖像管理功能、評論管理和自定義字段編輯器。

步驟8:添加一個新項目
點擊 Add New 菜單進(jìn)入到自定義文章類型編輯器,輸入電影標(biāo)題、內(nèi)容和設(shè)置特色圖像。
步驟9:發(fā)布
發(fā)布文章,點擊 View Movie Review 就可以在瀏覽器中查閱剛才添加的電影評論了。
為自定義文章類型創(chuàng)建 Meta Box
使用 Meta Box 機(jī)制可以幫助我們在 WordPress 的 Meta Box 系統(tǒng)中,添加 自定義文字類型 所需的各種字段,就不用再借助默認(rèn)的自定義字段編輯器了。
步驟1:注冊自定義函數(shù)
打開 Movie-Reviews.php 文件,添加下面的代碼到最后一個 ?> 的前面。這樣就注冊了一個函數(shù),可以在訪問WordPress管理界面調(diào)用它。
add_action( 'admin_init', 'my_admin' );
步驟2:自定義功能的實現(xiàn)
添加一段 my_admin 函數(shù)的執(zhí)行代碼來注冊一個 meta box ,并使它和 movie_reviews 這個自定義文章類型相關(guān)聯(lián)。
function my_admin() {
add_meta_box( 'movie_review_meta_box',
'Movie Review Details',
'display_movie_review_meta_box',
'movie_reviews', 'normal', 'high'
);
}
在這里,add_meta_box 是用來給自定義文章類型添加 meta boxes 的函數(shù),它的屬性說明如下:
movie_review_meta_box是所需的HTML的id屬性(is the required HTMLidattribute)Movie Review Details是 meta box 標(biāo)題中的可見文本內(nèi)容(is the text visible in the heading of the meta box section)display_movie_review_meta_box是顯示 meta box 內(nèi)容的回調(diào)(is the callback which renders the contents of the meta box)movie_reviews在 meta box 中顯示的自定義文章類型的名字(is the name of the custom post type where the meta box will be displayed)normal定義編輯器屏幕將顯示的頁面部分 (defines the part of the page where the edit screen section should be shown)high定義 boxes 在頁面中顯示位置的優(yōu)先級(defines the priority within the context where the boxes should show)
步驟3:實現(xiàn) display_movie_review_meta_box 函數(shù)的功能
<?php
function display_movie_review_meta_box( $movie_review ) {
// Retrieve current name of the Director and Movie Rating based on review ID
$movie_director = esc_html( get_post_meta( $movie_review->ID, 'movie_director', true ) );
$movie_rating = intval( get_post_meta( $movie_review->ID, 'movie_rating', true ) );
?>
<table>
<tr>
<td style="width: 100%">Movie Director</td>
<td><input type="text" size="80" name="movie_review_director_name" value="<?php echo $movie_director; ?>" /></td>
</tr>
<tr>
<td style="width: 150px">Movie Rating</td>
<td>
<select style="width: 100px" name="movie_review_rating">
<?php
// Generate all items of drop-down list
for ( $rating = 5; $rating >= 1; $rating -- ) {
?>
<option value="<?php echo $rating; ?>" <?php echo selected( $rating, $movie_rating ); ?>>
<?php echo $rating; ?> stars <?php } ?>
</select>
</td>
</tr>
</table>
<?php
}
?>
此代碼用來顯示 Meta box 的內(nèi)容。在這里,我們使用了一個對象變量(object variable),它包含了顯示在編輯器中的每一個電影評論(Movie Review)的信息。我們使用這個對象來檢索到文章的 ID,然后用它來查詢數(shù)據(jù)庫獲取對應(yīng)的導(dǎo)演(Director)的名字(name)和等級(Rating),并且返還顯示在meta box 中。當(dāng)添加了一篇新文章,然后 get_post_meta 返回一個空字符串導(dǎo)致在 meta box 中只顯示空的字段。
步驟 4: 注冊一個 Save Post 函數(shù)
add_action( 'save_post', 'add_movie_review_fields', 10, 2 );
該函數(shù)將在保存文章時調(diào)用。
步驟 5: 實現(xiàn) add_movie_review_fields 函數(shù)的功能
function add_movie_review_fields( $movie_review_id, $movie_review ) {
// Check post type for movie reviews
if ( $movie_review->post_type == 'movie_reviews' ) {
// Store data in post meta table if present in post data
if ( isset( $_POST['movie_review_director_name'] ) && $_POST['movie_review_director_name'] != '' ) {
update_post_meta( $movie_review_id, 'movie_director', $_POST['movie_review_director_name'] );
}
if ( isset( $_POST['movie_review_rating'] ) && $_POST['movie_review_rating'] != '' ) {
update_post_meta( $movie_review_id, 'movie_rating', $_POST['movie_review_rating'] );
}
}
}
當(dāng)保存文章或從管理面板中刪除文章時,將執(zhí)行該函數(shù)。如果是 movie_reviews 這個文章類型,就進(jìn)一步查看 meta box 元素是否已分配值,最后保存這些值到這些字段中。
步驟 6: 禁用默認(rèn)的自定義字段選項
在創(chuàng)建自定義文章類型時,我們已經(jīng)定義了一個函數(shù) create_movie_review。從支持?jǐn)?shù)組中移除自定義字段元素,因為它們再也用不到了。現(xiàn)在如果你保存了這個文件,然后打開 Movie Reviews 編輯頁面,你就可以在 meta box 中看到 Movie Author 和 Movie Rating 這兩個字段。當(dāng)然了,你也可以添加其他字段。

創(chuàng)建一個該自定義文章類型專用的模板
顯示自定義文章類型數(shù)據(jù)的正確方法是為每一個自定義文章類型創(chuàng)建專用的模板。下面,我們就來創(chuàng)建一個電影評論(Movie Review)專用的模板來顯示它的內(nèi)容。
步驟 1: 注冊一個函數(shù)來強(qiáng)制使用專用模板
打開 Movie-Reviews.php 文件,然后添加下面的代碼到php結(jié)束標(biāo)簽 ?> 的前面。這就注冊一個函數(shù),它會在訪問 WordPress 管理界面時被調(diào)用。
add_filter( 'template_include', 'include_template_function', 1 );
步驟 2: 實現(xiàn)該函數(shù)的功能
function include_template_function( $template_path ) {
if ( get_post_type() == 'movie_reviews' ) {
if ( is_single() ) {
// checks if the file exists in the theme first,
// otherwise serve the file from the plugin
if ( $theme_file = locate_template( array ( 'single-movie_reviews.php' ) ) ) {
$template_path = $theme_file;
} else {
$template_path = plugin_dir_path( __FILE__ ) . '/single-movie_reviews.php';
}
}
}
return $template_path;
}
上面的代碼會在當(dāng)前主題目錄搜索一個類似 single-(post-type-name).php 模板文件,如果沒有搜索到,它就會到這個插件的目錄來搜索,也即是我們下來要添加的插件文件。這個 template_include 掛鉤(hook)是用來更改默認(rèn)行為,并執(zhí)行特定的模板的。
步驟3:創(chuàng)建頁面(Single Page)模板
保存好上面編輯的那個文件后,創(chuàng)建一個名為 single-movie_reviews.php 的文件,然后在里面添加下面的代碼:
<?php
/*Template Name: New Template
*/
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php
$mypost = array( 'post_type' => 'movie_reviews', );
$loop = new WP_Query( $mypost );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<!-- Display featured image in right-aligned floating div -->
<div style="float: right; margin: 10px">
<?php the_post_thumbnail( array( 100, 100 ) ); ?>
</div>
<!-- Display Title and Author Name -->
<strong>Title: </strong><?php the_title(); ?><br />
<strong>Director: </strong>
<?php echo esc_html( get_post_meta( get_the_ID(), 'movie_director', true ) ); ?>
<br />
<!-- Display yellow stars based on rating -->
<strong>Rating: </strong>
<?php
$nb_stars = intval( get_post_meta( get_the_ID(), 'movie_rating', true ) );
for ( $star_counter = 1; $star_counter <= 5; $star_counter++ ) {
if ( $star_counter <= $nb_stars ) {
echo '<img src="' . plugins_url( 'Movie-Reviews/images/icon.png' ) . '" />';
} else {
echo '<img src="' . plugins_url( 'Movie-Reviews/images/grey.png' ). '" />';
}
}
?>
</header>
<!-- Display movie review contents -->
<div class="entry-content"><?php the_content(); ?></div>
</article>
<?php endwhile; ?>
</div>
</div>
<?php wp_reset_query(); ?>
<?php get_footer(); ?>
現(xiàn)在,我們已經(jīng)通過循環(huán)(loop)創(chuàng)建了一個基本的頁面模板。這個 函數(shù)檢索自定義文章類型的元素,并在循環(huán)中使用它們。當(dāng)然,這僅僅是一個基本的循環(huán),你可以根據(jù)自己想需要調(diào)整。你也可以使用適當(dāng)?shù)腃SS樣式來格式化那些元素。
注意:你需要在后臺創(chuàng)建一個新的頁面,并且選擇剛才創(chuàng)建的頁面模板。
步驟4:添加圖片
你需要添加2個 32*32 像素的星星圖標(biāo)到你的插件文件夾中。分別命名為 icon.png 和 grey.png 。好了,現(xiàn)在電影評論就會顯示在一個頁面上,并且按照日期排序。

在我的下一個教程《WordPress 自定義文章類型 介紹及實例解說(下)》,我的自定義文章類型應(yīng)包括更多的功能,如創(chuàng)建一個存檔頁面,創(chuàng)建自定義分類,自定義列等,請?zhí)峁┠膶氋F建議。
原文:http://wp.tutsplus.com/tutorials/plugins/a-guide-to-wordpress-custom-post-types-creation-display-and-meta-boxes/
編譯:胡倡萌@WordPress大學(xué) – wpdaxue.com (標(biāo)題有改動)
后話:倡萌的英語實在太爛了,翻譯這篇文章居然用了2個小時,有些地方還翻譯不準(zhǔn)確,望大家見諒。同時歡迎英文好的朋友指正,不勝感激!
您已閱讀完《實例講解 WordPress 自定義文章類型(共2篇)》專題的第 1 篇。請繼續(xù)閱讀該專題下面的文章:





好像很厲害的樣子
一直這么寫自定義分類,最近才發(fā)現(xiàn)有兩個嚴(yán)重的問題,不知道是什么地方寫錯了?
1、點擊后臺該分類的“篩選”按鈕(不選擇任何日期),第一次會篩選出類型為post的文章(而不是當(dāng)前的),第二次會顯示“無效的文章類型”。
2、在自定義文章類型的后臺列表中,有一個“搜索XXXX”,嘗試搜索時,只會列出默認(rèn)的post類型文章,而不是新建的類型。多次點擊“搜索xxxx”會出現(xiàn)和問題1一樣的問題,顯示“無效的文章類型”。
請問是什么地方錯了?
找到原因了,add_filter pre_get_posts的問題
? 求救啊,為什么我在新建Page時候,沒有在頁面屬性里,發(fā)現(xiàn)“模板”這兩個字,只有“父級”和“排序”,沒法應(yīng)用模板。(我是烤的源代碼)、
為什么我直接下載本文的源碼,添加到自定義文章沒辦法在前臺顯示?都是404報錯找不到頁面,也沒辦法預(yù)覽,只能在后臺存?zhèn)€檔而已,求解
請確保你的本地環(huán)境支持偽靜態(tài)固定鏈接結(jié)構(gòu),然后重新保存一次 設(shè)置 – 固定鏈接
感謝回復(fù),果然重新保存一次偽靜態(tài)就解決了
確實是很不錯的東西…特別是發(fā)送頁面到主題的模板選擇菜單的功能!實在是太經(jīng)典了!我就冒昧的轉(zhuǎn)載了
WordPress 是專為定制而生的,它的每一個節(jié)都是可定制的。
應(yīng)該是每一個細(xì)節(jié)
校長英語總之比我強(qiáng)…能把主題翻譯成英文還是不錯的。
保存了半天沒結(jié)果,發(fā)現(xiàn)原來少了Registering a Save Post Function。。。。。。樓主翻譯不要斷章啊。。。。。
多謝反饋,已補(bǔ)充完善。估計是當(dāng)時眼花跳過了
我有個問題,display_movie_review_meta_box是顯示內(nèi)容回調(diào);
那么我如何過濾、檢查、處理在提交過程中的數(shù)據(jù)呢?
太贊了!
這么牛逼的文章沒有人評論??