本文實例講述了WordPress使用自定義文章類型實現任意模板的方法。分享給大家供大家參考,具體如下:
這幾天在搭建博客的時候,碰到了一個對我來說很棘手的問題。WordPress自帶的文章類型只能使用他們特定的模版,而我由于想做一個心情時間軸的板塊,所以只能自定義文章的類型,讓他來支持我的這個模版。于是網上找資料,并且以插件的形式來表現,得到了如下的解決方案:
主要就是使用了register_post_type 函數。
1、創建插件目錄
新建一個文件夾用來存放插件文件,這里我就命名這個文件夾為myMood
2、創建PHP代碼文件
在剛才創建的文件夾里面新建一個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、注冊自定義函數
在剛剛創建的php文件代碼中,在?>前面添加函數:
得到如下代碼:
/*
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、添加函數功能
把下面這段代碼添加到 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 這個函數發出聲明,它就為新的文章類型做好了各種管理功能。這個函數包括兩個參數:第一個是定義了自定義文章類型的名字 ;第二個是一個數組,用來定義新的自定義文章類型的屬性。
第一個參數很簡單,大家自己領悟。這里簡單說下地位個參數:
'public' => true 決定該文章類型在管理后臺和前端的可見性
'menu_position' => 5 決定該文章類型菜單的位置
'supports' => array( 'title', 'editor', 'comments', 'thumbnail') 決定自定義文章類型的功能
'taxonomies' => array( '' ) 創建自定義分類,這里沒有定義。
'menu_icon' => plugins_url( 'image.png', __FILE__ ) 顯示管理菜單的圖標,圖標文件放在和插件同一目錄,為16*16像素
'has_archive' => true 啟用自定義文章類型的存檔功能
請訪問 register_post_type 了解更多關于該函數的參數細節。
6、創建一個該自定義文章類型的模版
打開剛剛的代碼文件,在
7、實現該函數的功能
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、創建單頁面模版single-lsxq.php
創建一個名字為single-lsqx.php的文件,主要代碼段如下:
$mypost = array( 'post_type' => 'lsxq', );
$loop = new WP_Query( $mypost );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
<div class="item">
<h3> <span class="fr"><?php the_time('Y-n-j H:i') ?></span> </h3>
<div class="con">
<?php the_content(); ?>
</div>
</div>
<?php endwhile; ?>
現在,我們已經通過循環創建了一個基本的頁面模板。這個 函數檢索自定義文章類型的元素,并在循環中使用它們。現在自定義文章類型差不多就好了,剩下的就是css樣式了。
上述代碼可點擊此處本站下載。
希望本文所述對大家基于wordpress的網站建設有所幫助。