WordPress: Custom Post Type Guide

One of the most anticipatedfeatures of WordPress 3.0 was the ability to add your owncustom post types to WordPress, which allows you to display andcategorize different types of content outside of the 5 nativeWordPress content types (i.e. Post, Page, Attachment, and soforth). The addition of this feature is a big step forward inmaking WordPress a full-fledged CMS, extending outside its normaluse as a blogging platform.

In this guide, we’ll go through the process of creating andusing your own custom post type. More specifically, we will createan "Event" post type for your special events and dates, sort oflike a calendar.

What is a Custom Post Type?

If you’re familiar with WordPress, then I’m sure you’ve alreadyhad some exposure to the default WordPress post types used forcontent creation: Post and Page. Almost all of the content in anyWordPress site prior to 3.0 is composed of some combination ofposts and pages.

Posts are generally used for content that is updated frequently(blog posts, for example), and pages are generally used for staticcontent (such as theAboutpage of a site).

Often, however, you may have a more specific type of data thatyou want to include on your site. This is where custom post typescome in.

We’re going to create a custom post type that we’ll call"Event". This content type will let us add events such asbirthdays, holidays, conference dates, and so forth.

We’ll be working with the default TwentyTentheme that comes with WordPress 3.0 so that we have a uniformcode base, but the concepts and techniques will be applicable toany theme.

Creating a Custom Post Type

Fortunately, WordPress makes it pretty easy to create a newcustom post type. Let’s look at the code first and then I’llexplain how it works:

add_action( 'init', 'create_events' );
function create_events() {
  $labels = array(
    'name' => _x('Events', 'post type general name'),
    'singular_name' => _x('Event', 'post type singular name'),
    'add_new' => _x('Add New', 'Event'),
    'add_new_item' => __('Add New Event'),
    'edit_item' => __('Edit Event'),
    'new_item' => __('New Event'),
    'view_item' => __('View Event'),
    'search_items' => __('Search Events'),
    'not_found' =>  __('No Events found'),
    'not_found_in_trash' => __('No Events found in Trash'),
    'parent_item_colon' => ''
  );

  $supports = array('title', 'editor', 'custom-fields', 'revisions', 'excerpt');

  register_post_type( 'event',
    array(
      'labels' => $labels,
      'public' => true,
      'supports' => $supports
    )
  );
}

The above code should be placed in thefunctions.php file of your theme.

A few notes about the code:

  • add_action tells WordPress to call ourcreate_events() function when WordPressinitializes
  • The $labels array tells WordPress how to displaymessages about our custom post type
  • The $supports array tells WordPress what our posttype supports (Can it have an excerpt? – for instance)
  • register_post_type actually registers our new posttype with WordPress
  • The register_post_type function is verycustomizable and has many more options than those that we areactually using; you can see all of these at theWordPressCodex.

Once we add this code to functions.php, we can seeour new post type in the WordPress Admin section.

WordPress Custom Post Type

Let’s go ahead and add and publish a new Event. You can publisha new Event just like you would a regular Post.

WordPress Custom Post Type

Displaying a Custom Post Type

Now that we’ve published our event, we can view it like anyother post. If you edit your event and then click on the "ViewEvent" button, you’ll see that the event is displayed like anyother post.

WordPress Custom Post Type

However, the reason we typically create a custom post type isbecause we want it to look and act differently from a regularpost.

Again, WordPress provides a nice mechanism for customizing howour custom post looks. If you’ve done work on WordPress themes inthe past, you probably know that a single blog post is displayedusing thesingle.php theme file. WordPress 3.0 allowsyou to add a single-[your_post_type_name].php file tooverride how a custom post type is displayed. Notice the format ofthis file name:single- followed by the name youassigned your custom post type.

For our Event type, create a single-event.php fileand copy the contents ofsingle.php into it. To keepit simple, we’ll just change one line insingle-event.php to show that it is really working.Find the line that is outputting the Event title insingle-event.php; it should look like thefollowing:

 <h1 class="entry-title"><?php the_title(); ?></h1>

Let’s change it to:

 <h1 class="entry-title">Event: <?php the_title(); ?></h1>

If we go back and look at our Event webpage now, we can see thatit is showing our changes.

WordPress Custom Post Type

Any other changes that you make to single-event.phpwill be visible when viewing an event.

Listing Our Custom Post Type

Now that we’ve seen how to display one of our events, how do wego about listing all of our events? Displaying single events isuseful, but its functionality is limited unless we can see all ofour events.

There are a couple of different ways to do this, butunfortunately, none of them are particularly straightforward. Themost common way (and the way we’ll do it here) is to display a listof custom post types through the use of a customPageTemplate. This process isn’t too complicated once you’ve doneit a couple of times, but it does require multiple steps.

First, copy the contents of page.php to a new filecalled page-events.php.

WordPress allows you to create as many different templates asyou want for displaying pages in different manners. We’re going touse this functionality to create a template for displayingevents.

In page-events.php, add the following linesomewhere in the comment at the top of the file:

           Template Name: Events Template
        

This line tells WordPress that the page-events.phpfile is a Page Template and that it is named "Events Template." Thetop part ofpage-events.php should now look somethinglike this:

<?php


get_header(); ?>

Next, use the following code right before the beginning of theWordPressLoop:

<?php query_posts(array('post_type'=>'event')); ?>

The Loop is the line that looks like this:

<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

The above code tells WordPress to find all content that has thetype of event and then to loop through them.

Now that we have a custom page template that will display ourevents, we need to actually create an "Events" page that willdisplay them. To do that, log back in to the WordPress adminsection, create a new page with the title of Events, and thenselect the "Events Template" for the Template page attribute.

WordPress Custom Post Type

Now that you’ve published the Events page using the EventsTemplate, you can go back to your site and should see the Eventspage. Depending on your theme, you may need to update yournavigation to include this new page. If we navigate to the Eventspage, we see that our events are now being listed!

WordPress Custom Post Type

Since our custom page template is listing all of the events, wecan edit that template if we want to change how the listing looks.We could, for instance, add a calendar icon next to each event,only show the event title, or really customize the page in any waywe wanted, just by editing the page-events.phpfile.

Summary

If you’ve made it this far, you now know how to create, design,display, and list custom post types in WordPress. We’ve justscratched the surface of what you can do with custom post types,but I’m sure you can see that they’re very useful for extendingWordPress’s CMS capabilities.

If editing theme files and coding is a little too intimidatingfor you, there are a couple of WordPress plugins that allow you toaccomplish much of the above (seeCustomPost Type UI andGDCustom Posts And Taxonomies Tools, among others).


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WordPress的'post'是指WordPress中的文章(post)类型。每个文章都有自己的标题、内容、发布日期等属性。在WordPress中,可以使用多种方法来获取和显示文章。 其中,可以使用WP_Query类来调用文章列表,并且可以按照自定义的条件进行筛选和排序。具体的方法是使用$args数组来设置查询参数,例如设置'post_type'为'product'、'posts_per_page'为10,然后使用循环和the_title()、the_content()函数来输出每篇文章的标题和内容。 另外,还可以使用get_posts函数来获取文章列表。该函数支持众多参数来选择需要提取的文章,例如设置'numberposts'为5、'orderby'为'post_date',然后将返回的文章存储在$posts_array数组中。 总之,WordPress的'post'是指文章类型,可以使用WP_Query类或get_posts函数来获取和显示文章列表。这些方法都可以根据自定义的条件进行筛选和排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [WordPress 自定义文章类型(Post Type)](https://blog.csdn.net/youcijibi/article/details/78490500)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [详解WordPress开发中的get_post与get_posts函数使用 (wordpress 提取 某个category 下的 post 数据)](https://blog.csdn.net/nysaisai/article/details/80437450)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值