WordPress Custom Post Types Guide


October 5th, 2010 by John Gadbois
http://sixrevisions.com/wordpress/wordpress-custom-post-types-guide/

WordPress Custom Post Types Guide

One of the most anticipated features of WordPress 3.0 was the ability to add your own custom post types to WordPress, which allows you to display and categorize different types of content outside of the 5 native WordPress content types (i.e. Post, Page, Attachment, and so forth). The addition of this feature is a big step forward in making WordPress a full-fledged CMS, extending outside its normal use as a blogging platform.

In this guide, we’ll go through the process of creating and using your own custom post type. More specifically, we will create an “Event” post type for your special events and dates, sort of like a calendar.

What is a Custom Post Type?

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

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

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

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

We’ll be working with the default TwentyTen theme that comes with WordPress 3.0 so that we have a uniform code base, but the concepts and techniques will be applicable to any theme.

Creating a Custom Post Type

Fortunately, WordPress makes it pretty easy to create a new custom post type. Let’s look at the code first and then I’ll explain 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 the functions.php file of your theme.

A few notes about the code:

  • add_action tells WordPress to call our create_events() function when WordPress initializes
  • The $labels array tells WordPress how to display messages about our custom post type
  • The $supports array tells WordPress what our post type supports (Can it have an excerpt? – for instance)
  • register_post_type actually registers our new post type with WordPress
  • The register_post_type function is very customizable and has many more options than those that we are actually using; you can see all of these at the WordPress Codex.

Once we add this code to functions.php, we can see our 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 publish a 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 any other post. If you edit your event and then click on the “View Event” button, you’ll see that the event is displayed like any other post.

WordPress Custom Post Type

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

Again, WordPress provides a nice mechanism for customizing how our custom post looks. If you’ve done work on WordPress themes in the past, you probably know that a single blog post is displayed using the single.php theme file. WordPress 3.0 allows you to add a single-[your_post_type_name].php file to override how a custom post type is displayed. Notice the format of this file name: single- followed by the name you assigned your custom post type.

For our Event type, create a single-event.php file and copy the contents of single.php into it. To keep it simple, we’ll just change one line in single-event.php to show that it is really working. Find the line that is outputting the Event title in single-event.php; it should look like the following:

 <h1><?php the_title(); ?></h1>

Let’s change it to:

 <h1>Event: <?php the_title(); ?></h1>

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

WordPress Custom Post Type

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

Continues here:
http://sixrevisions.com/wordpress/wordpress-custom-post-types-guide/

About these ads

Etiquetado:, , , , , , , ,

Un pensamiento en “WordPress Custom Post Types Guide

  1. Dbtlrhom 6 mayo 2012 en 9:24

    A Second Class stamp http://tynotiposy.de.tl little girlsporn gallery this was good, not sure if it should have been titled ‘hardcore’ but i liked it, it would have been better if he’d climaxed and they then kissed but perhaps the camera battery ran out?

Los comentarios están cerrados.

Cruces, Sol y La Imaginación

Cuando la imaginación y la creatividad suman infinito

MarketingActivo

el mundo del marketing se activa para ti

tranquicomix

fanzine bejarano de historietas hecho en los 80

A Stairway To Fashion

contact: ralucastoica23@gmail.com

Vinod833's Blog

This WordPress.com site is the bee's knees

Apasionada de las Redes Sociales

Compartir conocimientos 2.0 y Marketing Online

Zona de Promesas

Tecnología - Internet - Redes Sociales - Entrepreneurship - Música - Economía - Innovación

Top Master | Blog

LOS PROGRAMAS DE MBA Y POSTGRADO MAS INFLUYENTES DE TODO EL MUNDO

La realidad alterna

Diario de sueños, cuentos, poesías y una novela en proceso

TechCrunch

Startup and Technology News

Unencumbered by Facts

Taking unsubstantiation to new levels

Carlos Cordero

Blog de tecnología

PsicoEmocions Blog

Un Pont entre la Psique i les Emocions

TEA PTLS NACHO

AUTISMO.TEA..PTLS

Comunicación & Marketing

De Lilian Lanzieri

Xtratexia

Dirección estratégica para la vida

Silvia Altamirano

An editorial designer that writes

StellarHIRE Partners

Founding Partner, StellarHire Partners - Executive Search Consultants. Recent engagements include Eloqua, SFDC, Tibco and Veeam.

ivanbrunpr's Blog

4 out of 5 dentists recommend this WordPress.com site

Matt on Not-WordPress

Stuff and things.

BLOGTEC

Noticias de Tecnologia.

Talento en Expansión

Tendencias y Mejores Prácticas en la Gestión de Personas de la Empresa 2.0

Two Leaves Tea SPAIN

Great Organic Tea! ✫✫✫✫✫ Te Organico en Piramides

Escuela de Dinero

El mejor Sitio en Español sobre lo básico para entender el Dinero y sus matemáticas relacionadas.

Intentando dejar huella...

...en cada uno de los visitantes

Ideas Para la Clase.com

Portafolio de experiencias en la clase de español para Middle School.

littlegreybox

Travel & Lifestyle Blog

déborah rueda

Un sitio más pero diferente sobre marketing on line

No solo los 80's

La mejor música de la historia

Molly Balloon's Blog

Identity + Dressing + Colour

El OJO PUBLICO. / Глаз общественности

Ver para contar & contar para ver. / Чтобы рассказать

Think Creative Idea

Marketing, publicidad, web y negocios

Social Media y más

Social Media, Redes Sociales, Marketing, SEO

The Coaching Alliance

El camino hacia el éxito

Luces y sombras de las marcas

Social Media, Marketing y Comunicación

CNN en Español: Ultimas Noticias de Estados Unidos, Latinoamérica y el Mundo, Opinión y Videos

Ultimas Noticias de Estados Unidos, Latinoamérica y el Mundo, Opinión y Videos

Javier GM Photography - México y más.

“Un fotógrafo tiene que ser auténtico y en su obra, debe expresar emociones, provocar reacciones y despertar pasiones.” ~ Javier García-Moreno E.

Natalia Gómez del Pozuelo

Experta en comunicación y oratoria

aloyn

Alimentación, ocio y negocios, ALOYN, es un Grupo dirigido a Directivos y Propietarios de empresas, interesados en el mundo de la industria de alimentación y bebidas. Tanto por la parte de la industria productora como por la parte de la industria consumidora y/o distribuidora (Distribución Comercial, Horeca, Vending, Venta Directa, etc). También nos interesan las actividades ligadas al agroturismo y el enoturismo como magníficas actividades de promoción y difusión de la cultura gastronómica.

Blog de Jack Moreno

Un blog de Joaquín Moreno sobre recursos, literatura y ciencia ficción

Mashamour

Ensalada de Manjares

Infographic List

For those who love Infographics - www.infographiclist.com

URieLaRtE

hay que ser libre para ser uno mismo

Seguir

Recibe cada nueva publicación en tu buzón de correo electrónico.

Únete a otros 1.694 seguidores

A %d blogueros les gusta esto: