Cómo utilizar los campos personalizados en WordPress

Mientras escribías tu artículo anterior, es posible que te hayas desplazado sobre el área de Campos Personalizados en el editor de entradas.

Esta sencilla, pero tan potente función de WordPress, puede pasar desapercibida para los principiantes, pero en realidad es una función que puede, sin duda, transformar tu sitio web simple y sencillo en un portal dinámico que atraerá a nuevos visitantes.

Déjanos mostrarte más sobre los campos personalizados y cómo utilizarlos en tu sitio.

Índice de Contenido
  1. ¿Qué son los campos personalizados y cómo funcionan?
    1. Mostrar todos los campos personalizados:
    2. Display specific custom field:
    3. Conditional Custom Fields:
  2. How to list posts with a specific custom field
    1. 1. Create a custom template:
    2. 2. Add the page:
    3. 1. Prepare the template:
    4. 2. Using the sidebar in custom fields:
    5. 1. Prepare the file:
    6. 2. Replace the code:
    7. 3. Change a header via custom field:
  3. Implement Advanced Custom Fields more easily with ACF Theme Code
    1. ACF Theme Code
  4. Muestra tu estado de ánimo o una canción con campos personalizados
    1. 1. Añadamos una "función de humor":
    2. 2. Añade tu estado de ánimo/canción a un post:
    3. 3. Dale estilo:
  5. Resumiendo

¿Qué son los campos personalizados y cómo funcionan?

¿Qué son exactamente los campos personalizados? Estos pequeños campos permiten a cualquier usuario introducir información adicional sobre la entrada. Esto se conoce como metadatos, es decir, "datos sobre datos" y te permite adjuntar información adicional a tus posts. Los valores que puedes introducir en los campos personalizados pueden ir desde algo tan sencillo como añadir un texto o un número a tu entrada, añadir imágenes, cambiar los estilos a través del campo o, en realidad, hacer cualquier cosa que se te pase por la cabeza.

Campos personalizados

Quizá todo quede más claro con un ejemplo.

Imagina que diriges un sitio web dedicado a los videojuegos. Escribes noticias y publicas trailers, juegas con el hardware de los juegos para poder hablar de él y, por supuesto, escribes reseñas cuando llegan nuevos juegos. Después de escribir una reseña y colocar capturas de pantalla y vídeos de juego en el artículo, probablemente quieras mostrar información importante sobre el juego.

En lugar de ocultar la información más importante sobre un juego en el extenso texto, es posible que quieras mostrar la puntuación del juego, los nombres del desarrollador y del editor con un enlace a su sitio web, la fecha de lanzamiento, etc. Sí, los campos personalizados son algo que puede ayudarte a hacer la magia.

Si dejas que tus autores introduzcan esa información en un campo personalizado, puedes extraer fácilmente la información y mostrarla además de la reseña. Has visto infoboxes en sitios de reseñas. Si lo haces, todas las reseñas pueden tener una plantilla estandarizada, lo que puede mejorar la experiencia del usuario, tanto en la parte delantera como en la trasera.

Siguiendo el ejemplo del sitio web de juegos, acabarías teniendo varios campos personalizados que tus autores pueden introducir y que muestras a tus lectores:

Información sobre Call of Duty

Esta es la información que tus autores introducirían en los campos personalizados, y puedes mostrarla en un post. ¿Pero cómo?

Mostrar todos los campos personalizados:

Si sólo tienes un campo o quieres mostrar todos tus campos en el mismo lugar, puedes enganchar todos los metadatos a la vez con una simple función:

  1. Abrir single.php
  2. Busca la función the_content () y pega este código antes o después de ella (dependiendo de dónde quieras mostrar los campos personalizados):
  1. Save changes

Display specific custom field:

That’s it. That simple function will now stay hooked and it will show all custom fields from a post. But what if you want to show different field in a different position or if you only want to show one specific key? Then you will use a slightly different approach and define the key which will be displayed:

  1. Open single.php file
  2. Find the content and c/p the following:
<?php echo get_post_meta($post->ID, 'key', true); ?>
  1. Replace ‘key’ with the actual custom field you are using in a post. For example: ‘Publisher’
  2. Save changes

This function will check each and every post in the loop and search for a custom field named “Publisher”. If the key was found, its value will be displayed. You can further customize the way a custom field is being displayed by adding a class to it and style the class with CSS or you can directly enter HTML into the field value.

Conditional Custom Fields:

If you want to, you can use custom fields as conditional. Let stay with the example and let’s say there are times that you won’t be able to know a release date for the game you’re writing about. Instead of typing a custom field, you can automatize the process and tell WordPress to write “TBA” (to be announced) into Release Date field if there isn’t any data added by the user:

<?php $release_date = get_post_meta($post->ID, 
'Release Date', true);
if ($release_date) {
?>
<?php echo $release_date; ?>
<?php } else { ?>
<p>To Be Announced.</p>
<?php } ?>

OK, we’ll wrap it up from here. This is the most basic way of using custom fields. But now that you have covered the basics, you can actually do pretty much anything with them. You can, for example, show your mood or a song you’re listening to. Or, you can show a list of posts which contain specific key and/or value. The sky is the limit.

How to list posts with a specific custom field

Custom fields are a great way of extending your posts’ functionality. Instead of letting users deal with the code, you can let them enter a value in a custom field and do something with that information – there are endless possibilities.

Sometimes, when you are already using specific custom fields, you may need to list posts with those fields.

For example, if you are writing game reviews and already have different custom fields where you display publisher, genre, score, etc. in a separate information box in your review, you might want to display only games from that specific publisher, games from FPS genre or only those reviews with a score of 10.

This kind of information could really be interesting to your visitor. You can allow them to browse your game reviews in much more details or allow them to see the top 10 rated games on your site. Even if you don’t want to publish a new list, this method can help you with data mining – instead of creating an article from it, you can list all posts with certain property for research purposes only.

In our opinion, the best way of listing posts sorted by a custom field is by creating a new page template and showing a list on a new page. This method allows you to organize your pages and to easily use a new page for displaying what you need. In the following lines, we are about to show you how to find all posts with a specific custom field and/or its value and show it on a new page.

1. Create a custom template:

Let’s stay with the game review example where we want to display all games from Bethesda Softworks (did anyone say Fallout?). For starters, you will need to create and prepare a custom template:

  1. Create a custom page template and name it bethesda-games.php
  2. Copy and paste the following code into the file:
<?php
/*
Template Name: Bethesda games
*/
?>
<?php get_header(); ?>
<?div class="container">
<?div class="indent">
<?php
query_posts(array(
'meta_key' => 'publisher’,
'meta_value' => 'Bethesda'
));

if ( have_posts() ) while ( have_posts() ) : the_post();
echo '<?li>';
the_title();
echo '<?/li>';
endwhile;

wp_reset_query(); ?>
<?/div>
<?/div>
<?php get_footer(); ?>

  1. Save changes

The code is ready to go through all custom fields and to find only ‘Publisher’ keys with the value of ‘Bethesda’. You can change the key and value to anything you want. If you would like to display all posts with ‘Publisher’ custom field containing any value, simply remove ‘meta_value’ row entirely.

Don’t forget to change the title of the template to something you will recognize later.

2. Add the page:

Now your template is ready so you can continue creating the list:

  1. Navigate to Pages->Add New
  2. Add a title
  3. On the right side, find “Page Attributes”
  4. Select your template from the “Template” dropdown list
  5. Publish the page

That’s it! Now if you open your new page, you can see the list of all your posts which contain custom fields with the values you have chosen.

Now you have to add some text to your new page, style the list and find the best way to show it to your visitors. We hope that this method will help you sort your posts on a whole other level and that you will enjoy it.

A sidebar was introduced in WordPress version 2.2. Since then, it has become a popular way of showing extra content and more often than not, WordPress themes will have one by default where you can place any widgets you want.

Although very useful, you don’t want your sidebar to be present everywhere. Usually, these bars are shown anywhere but the home page. And there is no such option to easily turn the sidebar on and off.

So, why not make it yourself. In this part of the article, we will show you how to put your sidebar into a custom field and call it only for posts you want.

1. Prepare the template:

  1. Open page.php or single.php file
  2. Find the following code: <?php get_sidebar(); ?>
  3. Replace the code with this one:
<?php $sidebar = get_post_meta($post->ID, 
"sidebar", true);
get_sidebar($sidebar);
?>
  1. Save changes
  2. Create a custom template where your sidebar will be
  3. Open the sidebar.php file
  4. Copy everything from sidebar.php and paste into your custom template file
  5. Save changes.

Now you have to open a post or a page where you can find “custom fields” under the Text/Visual Editor. To add a sidebar to that post/page, do the following.

2. Using the sidebar in custom fields:

  • Type “sidebar” under the name of your custom field
  • Type the name of your custom template as a field value

That’s it. If you have left your custom fields empty, your post will be without sidebar while in the other case, your sidebar should load if you have done everything correctly.

Usually, a WordPress website will have only one header, footer and sidebar already defined by the theme you are using. Each one has its functions and design stored in separate files which are called by the theme and then displayed on the site where needed. Because each part of the theme is stored in a different file, you can easily modify them without worrying you will mess up the entire site, and you can change the way only a header, footer or sidebar behaves on your site.

But sometimes, one element won’t be enough and for example, you will want to change your header. If you want to change it for the entire site, you’re already ready to go – open header.php and modify it the way you want it. But what if you wanted to add an ad in a header only for your single posts? Or maybe modify the header only for one post in your entire collection without changing the rest?

Once again, custom fields will help you.

1. Prepare the file:

Before we use a custom field to change headers, footers or sidebars, you should have a file prepared. Let’s say you want to change a header for a post or two and you have created a new file called header-header2.php where you have changed the design or inserted a specific advertisement to the post. Before you can continue with creating a custom field, make sure that the file is coded properly and is working on your site. Once the file is up and ready, you may proceed.

Be careful about naming the file – if you are trying to change the header, your new header file should look like this: header-newname.php

2. Replace the code:

  1. Open single.php file
  2. Search for get_header(); part of the code which is usually on the very top of the single.php page
  3. Replace the function with the following:
global $wp_query;
$postid = $wp_query->post->ID;
$header = get_post_meta($postid, "header", true);
if (!empty($header)) {
get_header($header);
} else {
get_header();
}
wp_reset_query();
  1. Save changes

With this code, you told WordPress to check for a “header” custom field in every single post. If a custom field with that name was found, WordPress will take its value and use the filename as a header for that post only.

3. Change a header via custom field:

If you have header-header2.php uploaded in your theme, you can now call it in a custom field:

  1. Open a post for which you want to change a header
  2. Scroll down and navigate to custom fields
  3. Enter a new field and name it “header”
  4. Type in “header2.php” in the field’s value
  5. Update or publish the post

If there aren’t any errors in your header-header2.php file, the new header should appear on top of the post for which you’ve made the change. Still, all the other posts will load your standard header file defined by the theme.

As you may have noticed, you are only required to type in the filename of your new header file after the “header-” part. Because of that, it is important to name your new header file correctly and add “header-“ part before the actual name you’re using in the custom field.

The same goes for sidebar or footer file, of course, by changing get_sidebar() and get_footer() part of the code.

Implement Advanced Custom Fields more easily with ACF Theme Code

Custom Fields are the inevitable part of practically every WordPress theme out there. These fields allow everyone to include extra information about the post, but unfortunately, this standard WP feature is quite raw. Beginners need some time to get accustomed to using custom fields and developers have to spend a lot of extra time when coding around them.

That’s the reason why Advanced Custom Fields (ACF) plugin is so popular among WordPress users all over the world. This free plugin counts more than 1 million active installs at this moment, and we don’t see why the number will start dropping. ACF allows you to create powerful, professional, and intuitive custom fields through a visual editor.

Although quite popular, ACF still requires coding knowledge and a lot of your time if you plan on implementing those fields in a theme. Yes, creating a field group is easy, but displaying those fields isn’t such a piece of cake. And that’s where ACF Theme Code steps in to save developers.

ACF Theme Code

PRICE: Free

Código del tema ACF para WordPress

Este impresionante plugin es el producto de dos desarrolladores que decidieron que ya era hora de dejar de perder el tiempo escribiendo repetidamente el mismo código una y otra vez. Al desarrollar un tema o modificar uno existente, Advanced Custom Fields requiere que un desarrollador implemente el código correcto en el lugar adecuado dentro de un tema. Como no había una manera más fácil, un desarrollador tenía que memorizar los fragmentos y todas las características de una API para poder hacer el trabajo.

Aaron Rutley, uno de los creadores, explicó en su blog:

" Al implementar un campo dentro de un tema de WordPress, es probable que olvide el nombre del campo, ¿era 'profile_image' o 'profile_photo'? También es probable que olvide cómo he configurado ese campo para que sea devuelto, ¿era ID, URL o Array? Me encontré editando constantemente el grupo de campos para averiguarlo"

Y aquí es donde ACF Theme Code puede ayudar a un desarrollador. Después de instalar este plugin gratuito que ya se ha descargado más de 4.000 veces, podrás ahorrar tiempo al tratar con el código. Cada vez que publiques, edites o actualices un grupo de campos en Advanced Custom Fields, este increíble plugin generará automáticamente el código necesario para implementar los campos en cualquier tema.

Encontrarás este código generado en la parte inferior de la página. Junto a cada fragmento, encontrarás un icono en el portapapeles que te facilitará la copia del código Ahora no tienes que memorizar nada y puedes relajarte cuando trabajes con campos personalizados.

Aunque el plugin ya es imprescindible para cualquier desarrollador, Aaron dice que ya están planeando ampliar ACF Theme Code:

"Tenemos previsto añadir soporte para más campos populares de terceros en el futuro. También planeamos dar a los desarrolladores más control sobre el código que se genera"

Aunque el plugin es gratuito si se combina con la versión gratuita de ACF, necesitarás un Versión PRO si utilizas una versión ampliada de Advanced Custom Fields. ACF Theme Code Pro genera código para todos los demás tipos de campos ACF Pro, como el campo Clon, Galería, Repetidor y Contenido Flexible.

Muestra tu estado de ánimo o una canción con campos personalizados

Escribir un blog debe ser divertido. Aunque escribas artículos sobre temas serios, tu blog puede tener alguna que otra cosa que lo haga más divertido para un lector medio. Puede ser cualquier cosa: una pequeña nota del autor, una imagen divertida o tal vez puedas añadir un estado de ánimo en el que te encontrabas mientras escribías el artículo. Tal vez incluso quieras añadir el título de una canción que estabas escuchando.

En esta parte, vamos a mostrarte cómo implementar fácilmente una función para mostrar un estado de ánimo/una canción en tus mensajes. No tendrás que instalar ningún plugin adicional y la función no ocupará mucho espacio. Es una simple línea de texto que se puede añadir automáticamente en la parte superior o inferior de tu post.

1. Añadamos una "función de humor":

  1. Abre el archivo single.php
  2. Copia y pega el siguiente código en el lugar donde quieras mostrar tu estado de ánimo:
$customField = get_post_custom_values("estado de ánimo");
if (isset($customField[0])) {
echo "" . "Estado de ánimo: "
.$customField[0] . "";
}
  1. Guardar los cambios
Estado de ánimo de los campos personalizados

Ahora que has preparado a WordPress para tus estados de ánimo, estás listo para mostrarlos en cualquier entrada que quieras. Por defecto, WordPress no mostrará tu estado de ánimo y no habrá ningún estado de ánimo por defecto que cargue hasta que decidas mostrar uno. Si quieres añadir una canción en su lugar, simplemente cambia el "estado de ánimo" por "canción" en la primera línea de código y también puedes cambiar el nombre de la clase en la tercera línea.

2. Añade tu estado de ánimo/canción a un post:

Para introducir un estado de ánimo o una canción, tendrás que escribirlo en un campo personalizado:

  1. Abre una entrada para la que quieras escribir un estado de ánimo
  2. Desplázate hacia abajo hasta que veas "Campos personalizados".

Si no tienes campos personalizados debajo del contenido de la entrada, haz clic en "Opciones de pantalla" en la parte superior de tu pantalla de editor y marca la casilla de verificación junto a "Campos personalizados".

  1. Escribe "estado de ánimo" en el campo del nombre o "canción" si te has decidido por él
  2. Escribe lo que quieras en el campo "Valor" - este será el estado de ánimo/canción que aparecerá en tu post
  3. Haz clic en el botón "Añadir campo personalizado"
  4. Publica tu entrada

3. Dale estilo:

Como ya puedes ver en sólo tres líneas de código, ésta es la forma más sencilla de añadir un nuevo campo personalizado. Si quieres estilizar el estado de ánimo con algo de CSS, puedes ver que el código ya ha añadido la clase "mi_estado de ánimo" a tu texto. Para modificar el estilo, haz lo siguiente:

  1. Abre el archivo style.css
  2. Copia y pega el código:
  1. Añade el estilo CSS que quieras
  2. Guarda los cambios.

Esperamos que esto sea suficiente para que empieces a personalizar "la función de estado de ánimo/canción" para tu propio blog y esperamos que "azul" no sea un valor frecuente con el que tengas que lidiar. Si no quieres publicar tu estado de ánimo, simplemente no escribas nada en el campo personalizado "estado de ánimo".

Resumiendo

Si alguien ha creado un campo personalizado para ti (como un desarrollador de temas o de plugins), utilizarlo para mejorar tu blog es bastante fácil. Pero esperamos que este artículo te haya ayudado a personalizar los campos por tu cuenta.

Con unas sencillas modificaciones en el código que te hemos mostrado, puedes crear y gestionar tus propios campos personalizados que te ayudarán a generar un blog único. Podrás extraer la información que necesites, y simplificarás el proceso de escribir y generar contenido. ¿Qué opinas de los campos personalizados en WordPress?

Si quieres conocer otros artículos parecidos a Cómo utilizar los campos personalizados en WordPress puedes visitar la categoría Tutoriales.

¡Más Contenido!

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Go up