Working with WordPress Custom Post Types

One of the major features to be introduced in WordPress 3 was the ability to create custom post types. Basically, this lets you recreate the ‘Posts’ tab with specific functionality in mind. For example, creating a portfolio with fields for project images and client information. At Shockoe, we are using this in an upcoming project to that uses WordPress to provide content for a new iPhone app.

This makes WordPress much more viable as a CMS as opposed to blogging software that struggles to handle larger sites. In previous versions of WordPress this involved either a considerable amount of work or using a massive plugin. The best of those plugins, Magic Fields (a fork of Flutter), is several thousand lines of code. We can create a flexible solution in far fewer lines.

Code in action

[cc lang="php"]
add_action(‘init’, ‘post_type_example’);
function post_type_example() {
register_post_type(
‘example’,
array(
‘label’ => __(‘Example’),
‘public’ => true,
‘show_ui’ => true,
‘supports’ => array(
‘title’,
‘editor’,
‘excerpt’,
‘comments’),
‘menu_position’ => 5
)
);

register_taxonomy( ‘categories’, ‘example’, array( ‘hierarchical’ => true, ‘label’ => __(‘Categories’) ) );
register_taxonomy( ‘tags’, ‘example’, array(‘label’ => __(‘Tags’)));
}[/cc]

Here we have created a new post type that will have it’s own sidebar tab under ‘Posts’ as well as fields for title, content (‘editor’), an excerpt, and comments. We also added functionality similar to WordPress’ tags and categories features by calling ‘register_taxonomy.’ Setting ‘hierarchal’ => true will make the field behave like categories while leaving it empty (or setting it to ‘false’) gives us the tags functionality.

That’s it. Simple. In a handful of lines we have a flexible solution that gives us the option of using better contextual grammar. That translates to a much better experience for clients and end users.

Adding Custom Functionality

The code above basically replicates the Posts functionality with the ability to have better labels. But what if we need to include custom information? For that we need add_meta_box:

[cc lang="php"]add_action(“admin_init”, “admin_init”);
function admin_init(){
add_meta_box(“example_field”, “Example Text Field”, “example_field”, “normal”, “high”);
}

function example_field () {
global $post;

$post_custom = get_post_custom($post->ID);
$text_field_content = $post_custom['text_field'][0];

print ”


“;
}[/cc]

And to save our custom field’s information when we press ‘Publish’:

[cc lang="php"]add_action(‘save_post’, ‘save_details’);
function save_details(){
global $post;

update_post_meta($post->ID, ‘text_field’, $_POST['text_field']);
}
[/cc]

Now we should have a custom text box that will appear below the content editor. When we save our post, the information in our custom field will be saved to the database. And when we edit our post, the text field will be repopulated.

Conclusion

With a little bit of coding knowledge you can create an elegant solution for turning WordPress into a functional CMS. And this is a very basic example; the possibilities of what can be created from this point are endless.

For more detailed information, see the register_post_type and add_meta_box reference pages in the WordPress Codex.

Este articulo esta siendo traducido. Por ahora puedes revisar la traducción que google nos da. No es igual, pero nos ayuda por ahora.

[traducido con google - translate]

Una de las características fundamentales que conviene introducir en WordPress 3 era la capacidad de crear tipos de correos. Básicamente, esto le permite recrear la pestaña “Mensajes” con una funcionalidad específica en mente. Por ejemplo, la creación de una cartera con campos para proyectar imágenes e información del cliente. En Shockoe, estamos usando esto en un próximo proyecto a que utiliza WordPress para ofrecer contenido de una aplicación para el iPhone nuevo (se está construyendo con Titanium.)

Esto hace que sea mucho más viable WordPress como CMS en lugar de software de blogs que lucha por manejar grandes sitios. En versiones anteriores de WordPress esta intervenir, ni una cantidad considerable de trabajo o usando un plugin masiva. Lo mejor de los plugins, Campos Magic (un tenedor de trémolo), es varios miles de líneas de código. Podemos crear una solución flexible en las líneas de un número mucho menor.

Código en acción

[cc lang="php"]
add_action(‘init’, ‘post_type_example’);
function post_type_example() {
register_post_type(
‘example’,
array(
‘label’ => __(‘Example’),
‘public’ => true,
‘show_ui’ => true,
‘supports’ => array(
‘title’,
‘editor’,
‘excerpt’,
‘comments’),
‘menu_position’ => 5
)
);

register_taxonomy( ‘categories’, ‘example’, array( ‘hierarchical’ => true, ‘label’ => __(‘Categories’) ) );
register_taxonomy( ‘tags’, ‘example’, array(‘label’ => __(‘Tags’)));
}[/cc]

Aquí hemos creado un tipo nuevo puesto que tendrá su propia pestaña en la barra lateral “Entradas”, así como campos de título, el contenido (“editor”), un extracto, y los comentarios.También hemos añadido una funcionalidad similar a las etiquetas de WordPress y características categorías llamando ‘register_taxonomy. “Jerárquico => Configuración’ true hará que el terreno se comportan como las categorías y se deja vacío (o el que éste se ocultaba en ‘false’) nos da la funcionalidad de etiquetas .

Eso es todo. Simple. En un puñado de líneas que tenemos una solución flexible que nos da la opción de utilizar mejor la gramática contextual. Eso se traduce en una experiencia mucho mejor para los clientes y usuarios finales.

Agregando funcionalidad personalizada

El código anterior, básicamente, replica la funcionalidad de Puestos con la posibilidad de tener mejores etiquetas. Pero ¿y si tenemos que incluir información personalizada? Para eso necesitamos add_meta_box:

[cc lang="php"]add_action(“admin_init”, “admin_init”);
function admin_init(){
add_meta_box(“example_field”, “Example Text Field”, “example_field”, “normal”, “high”);
}

function example_field () {
global $post;

$post_custom = get_post_custom($post->ID);
$text_field_content = $post_custom['text_field'][0];

print ”


“;
}[/cc]

Y para guardar la información de nuestros campos personalizados cuando se pulsa en “Publicar”:

[cc lang="php"]add_action(‘save_post’, ‘save_details’);
function save_details(){
global $post;

update_post_meta($post->ID, ‘text_field’, $_POST['text_field']);
}
[/cc]

Ahora debemos tener un cuadro de texto personalizado que aparecerá debajo del editor de contenidos. Al salvar a nuestro correo, la información en nuestro campo personalizado se guarda en la base de datos. Y cuando editamos nuestro puesto, el campo de texto se vuelve a llenar.

Conclusión

Con un poco de codificación de conocimientos, se puede crear una solución elegante para convertir WordPress en un CMS funcionales. Y este es un ejemplo muy básico, las posibilidades de lo que puede crearse a partir de este punto son infinitas.

Para obtener más información detallada, vea el register_post_type y páginas add_meta_box de referencia en el Codex de WordPress.

CEO and Co-founder of Shockoe.com, LLC
Entrepreneur and experienced software engineer, interested in everything that involves mobile technology.

Twitter 


Published :    By : edwin   Tags : , , ,    Cat :    Comments : 0