您的位置: INN823.com - 探讨 - 在 wordpress 3.0 中创建自定义内容类型

在 wordpress 3.0 中创建自定义内容类型

首先,什么是自定义内容类型呢?简单地说,自定义内容类型就是一个可以自定义的一篇博客文章或页面。例如,我想在一个博客上创建一个 优惠码列表,本来可以使用一个静态页面,但是以后如果要更新和添加新的优惠码就有点头疼了。因此,我创建了一个叫做“优惠(coupon)”的自定义内容类型以及一个页面模板来显示所有的优惠码,这样一来,管理这些优惠码就变得非常容易了:

创建自定义内容类型

首先要做的就是在主题 functions.php文件里添加下面的代码来创建一个自定义内容类型:

function create_my_post_types() {
register_post_type(‘coupons’,
array(
‘label’ => __(‘Coupons’),
’singular_label’ => __(‘Coupon’),
‘public’ => true,
’supports’ => array(
‘title’,
‘excerpt’,
‘comments’,
‘custom-fields’
),
‘rewrite’ => array(
’slug’ => ‘coupons’,
‘with_front’ => false
),
)
);
}
add_action( ‘init’, ‘create_my_post_types’ );

保存 functions.php文件后,在WordPress后台控制面板你就会发现一个新的标签,如下图所示:

这段代码是怎么回事呢?
首先,我创建一个函数来注册一个新的内容类型,并命名为“coupons”,register_post_type()函数利用了下面的参数:

  • label: 自定义内容类型的名称
  • singular_label: 自定义内容类型的单数形式。
  • public: 允许内容类型公开可见。
  • supports: 自定义内容类型支持的数据组 (编辑、摘要、评论、自定义字段等等…)
  • rewrite:URL重写的参数以及普通内容类型显示的参数。

完整的参数列表可参考WordPress Codex
最后,我通过使用add_action()将这个函数到勾选到WordPress init()函数上。

添加数据

现在自定义内容类型已经创建完了,你可以通过点击WordPress后台菜单的“Add Coupon”添加数据。
你将会看到下图所示:

创建一个页面模板来显示自定义内容类型

在完成自定义内容创建并添加了一些内容之后,我们还需要将它显示出来。这里,我使用了一个页面模板。

<?php
/*
模板名称: Promo codes Page
*/
?>
<?php get_header() ?>

<div id=”container”>
<div id=”content”>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>

<?php global $wp_query;
$page_num = $paged;
if($pagenum=”) $pagenum=1;

$wp_query = new WP_Query(“showposts=20&post_type=coupons&post_status=publish&paged=”.$page_num);

while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

<div id=”post-<?php the_ID(); ?>”>
<h2><?php the_title(); ?></h2>
<div><?php the_excerpt(); ?></div>
</div><!– .post –>

<?php endwhile; ?>

<div><p><?php posts_nav_link(); ?></p></div>

</div><!– #content –>
</div><!– #container –>

<?php get_sidebar() ?>
<?php get_footer() ?>

上面的代码都非常简单也容易理解,为了获取特定内容类型,你需要指定参数 post_type=coupons。

From: Reprinted

发表评论