先來(lái)看WordPress自定義類型實(shí)例
除了以上的保留文章類型外,為了滿足多樣化需求,我們可以自定義一些文章類型,例如:公告、視頻、專題等等,自定義文章類型的實(shí)際用途很廣,可以制作出復(fù)雜多變的表現(xiàn)形式,先來(lái)看看一個(gè)簡(jiǎn)單自定義類型的例子:
實(shí)例代碼如下:
- add_action( 'init', 'create_post_type' );
- function create_post_type() {
- register_post_type( 'acme_product',
- array(
- 'labels' => array(
- 'name' => __( 'Products' ),
- 'singular_name' => __( 'Product' )
- ),
- 'public' => true,
- 'has_archive' => true,
- )
- );
- }
在這個(gè)例子中我們創(chuàng)建了一個(gè)名為acme_product的文章類型,從上面可知道自定義文章類型主要是用了一個(gè)函數(shù)register_post_type,這個(gè)函數(shù)為注冊(cè)文章類型函數(shù),通過(guò)它可以注冊(cè)新的文章類型,其基本用法如下:
<?php register_post_type( $post_type, $args ); ?>
其中的$post_type為必需項(xiàng),定義文章類型的名稱,$args為可選項(xiàng),用來(lái)配置一些數(shù)組,關(guān)于$args的數(shù)組,參數(shù)非常多.
判斷當(dāng)前文章是不是自定義內(nèi)容類型
其實(shí)這樣的功能實(shí)在非常的簡(jiǎn)單,在根據(jù)當(dāng)前內(nèi)容的id就可以使用get_post等等函數(shù)返回這個(gè)內(nèi)容的對(duì)象,對(duì)象中就有一個(gè)post_type的方法,但是在老外的博客看到了,我想還是翻譯一下,代碼如下:
- function is_custom_post_type() {
- global $wp_query;
- $post_types = get_post_types(array('public' => true,'_builtin' => false),'names','and');
- foreach ($post_types as $post_type ) {
- if (get_post_type($post_type->ID) == get_post_type($wp_query->post->ID)) {
- return true;
- } else {
- return false;
- }
- }
- }
把上面的代碼放到主題的functions.php文件中就可以使用如下的函數(shù)判斷,代碼如下:
- if (is_custom_post_type()) {
- //如果內(nèi)容類型為自定義類型則返回true否則返回false
- }
新聞熱點(diǎn)
疑難解答
圖片精選