本文實例講述了WordPress使用自定義文章類型實現(xiàn)任意模板的方法。分享給大家供大家參考,具體如下:
這幾天在搭建博客的時候,碰到了一個對我來說很棘手的問題。WordPress自帶的文章類型只能使用他們特定的模版,而我由于想做一個心情時間軸的板塊,所以只能自定義文章的類型,讓他來支持我的這個模版。于是網(wǎng)上找資料,并且以插件的形式來表現(xiàn),得到了如下的解決方案:
主要就是使用了register_post_type 函數(shù)。
1、創(chuàng)建插件目錄
新建一個文件夾用來存放插件文件,這里我就命名這個文件夾為myMood
2、創(chuàng)建PHP代碼文件
在剛才創(chuàng)建的文件夾里面新建一個php文件,命名為myMood,用來書寫插件代碼
3、添加頭部描述
/*
Plugin Name: Movie Reviews
Plugin URI: http://wp.tutsplus.com/
Description: Declares a plugin that will create a new post type .
Version: 1.0
Author: Summer
Author URI: http://www.xtwind.com/
License: GPLv2
*/
?>
4、注冊自定義函數(shù)
在剛剛創(chuàng)建的php文件代碼中,在?>前面添加函數(shù):
得到如下代碼:
/*
Plugin Name: Movie Reviews
Plugin URI: http://wp.tutsplus.com/
Description: Declares a plugin that will create a new post type .
Version: 1.0
Author: Summer
Author URI: http://www.xtwind.com/
License: GPLv2
*/
add_action( 'init', 'create_myMood' );
?>
5、添加函數(shù)功能
把下面這段代碼添加到 add_action( 'init', 'create_myMood' ); 的前面
register_post_type( 'lsxq',
array(
'labels' => array(
'name' => '零散心情',
'singular_name' => 'lsxq',
'add_new' => '寫心情',
'add_new_item' => '添加一條新心情',
'edit' => 'Edit',
'edit_item' => 'Edit lsxq',
'new_item' => 'New lsxq',
'view' => 'View',
'view_item' => 'View lsxq',
'search_items' => 'Search lsxq',
'not_found' => 'No lsxq found',
'not_found_in_trash' => 'No lsxq found in Trash',
'parent' => 'Parent lsxq'
),
'public' => true,
'menu_position' => 15,
'supports' => array( 'title', 'editor', 'comments', 'thumbnail' ),
'taxonomies' => array( '' ),
'menu_icon' => plugins_url( 'images/image.png', __FILE__ ),
'has_archive' => true
)
);
}
對 register_post_type 這個函數(shù)發(fā)出聲明,它就為新的文章類型做好了各種管理功能。這個函數(shù)包括兩個參數(shù):第一個是定義了自定義文章類型的名字 ;第二個是一個數(shù)組,用來定義新的自定義文章類型的屬性。
第一個參數(shù)很簡單,大家自己領(lǐng)悟。這里簡單說下地位個參數(shù):
'public' => true 決定該文章類型在管理后臺和前端的可見性
'menu_position' => 5 決定該文章類型菜單的位置
'supports' => array( 'title', 'editor', 'comments', 'thumbnail') 決定自定義文章類型的功能
'taxonomies' => array( '' ) 創(chuàng)建自定義分類,這里沒有定義。
'menu_icon' => plugins_url( 'image.png', __FILE__ ) 顯示管理菜單的圖標(biāo),圖標(biāo)文件放在和插件同一目錄,為16*16像素
'has_archive' => true 啟用自定義文章類型的存檔功能
請訪問 register_post_type 了解更多關(guān)于該函數(shù)的參數(shù)細(xì)節(jié)。
6、創(chuàng)建一個該自定義文章類型的模版
打開剛剛的代碼文件,在
7、實現(xiàn)該函數(shù)的功能
if ( get_post_type() == 'lsxq' ) {
if ( is_single() ) {
if ( $theme_file = locate_template( array ( 'single-lsxq.php' ) ) ) {
$template_path = $theme_file;
} else {
$template_path = plugin_dir_path( __FILE__ ) . '/single-lsxq.php';
}
}
}
return $template_path;
}
該代碼段添加在下面語句的后面
8、創(chuàng)建單頁面模版single-lsxq.php