Advertisement
  1. Code
  2. Creative Coding

Utilizar Campos Personalizados para Crear una Sección de Valoraciones

Scroll to top
Read Time: 9 min

Spanish (Español) translation by Eva Collados Pascual (you can also view the original English article)

Las opiniones, reseñas o valoraciones de clientes son quizá uno de los recursos más poderosos de los que dispone un blog para respaldar su reputación. Si se implementan correctamente (con duro trabajo e información consistente), los blogs de valoraciones son sin duda una de las categorías más rentables de la blogosfera. Pero todo blog debe ofrecer un sólido diseño en sus entradas, incluído el diseño de las reseñas. En este artículo hablaremos sobre cómo crear una sección para perfecta para esas valoraciones, ya probablemente sea la sección que los usuarios consultarán en primer lugar, incluso antes de leer detalladamente una opinión.


Lo Que Vamos a Crear

Como ejemplo, vamos a crear una sección para la reseña de una película.

Usaremos como ejemplo una de mis películas favoritas, The Pursuit of Happyness. Vamos a mostrar la siguiente información sobre la película:

  • Nombre: The Pursuit of Happyness
  • Año: 2006
  • Director: Gabriele Muccino
  • Guionista: Steve Conrad
  • Actores: Will Smith, Jaden Smith, Thandie Newton
  • Género: Biográfica, Drama
  • Duración: 117 minutos
  • Argumento: Basada en una historia real sobre un hombre llamado Christopher Gardner. Gardner ha invertido mucho en un dispositivo conocido como un "analizador de la densidad ósea". Y siente que ha creado el mismo estos dispositivos. Sin embargo, no son comercializados al ser mejores que la tecnología existente en ese momento y cuyo precio es bastante superior. Cuando Gardner intenta averiguar cómo poder venderlos, su esposa lo abandona, pierde su casa, su cuenta bancaria y sus tarjetas de crédito. Forzado a vivir en la calle con su hijo, Gardner se encuentra ahora desesperado e intentando encontrar un trabajo estable; empieza a trabajar como corredor de bolsa, pero antes de recibir su primer sueldo debe formarse durante 6 meses y vender sus dispositivos.
  • (no nos olvidemos de que necesitamos una imagen).

Importante: Esta información está extraída de The Internet Movie Database (IMDb).


Paso 1: Preparar el Campo Meta Personalizado que Contendrá la Información

Vamos a almacenar los datos como valores de campos personalizados, pero añadir manualmente los campos personalizados de cada reseña sería una labor muy tediosa. Por eso, vamos a crear una sencilla caja meta personalizada para guardar nuestra información como campos personalizados.

Primero, necesitamos usar la función add_meta_box() para crear la caja meta y también crear una función callback:

1
2
function wptuts_review_box_add_meta() {
3
  add_meta_box( 'review-box', 'The Review Box', 'wptuts_review_box_meta', 'post', 'normal', 'high' );
4
}
5
add_action( 'add_meta_boxes', 'wptuts_review_box_add_meta' );
6
7
function wptuts_review_box_meta() {
8
	// Hi there!

9
}

La función callback creará el campo de entrada que contendrá nuestros datos. Creo que podemos usar una área de texto para el campo del "argumento" y campos de entrada de texto para todo lo demás:

1
2
<?php
3
function wptuts_review_box_meta($post) {
4
    global $post;
5
    // get the custom field values (if they exist) as an array

6
    $values = get_post_custom( $post->ID );
7
    // extract the members of the $values array to their own variables (which you can see below, in the HTML code)

8
    extract( $values, EXTR_SKIP );
9
    wp_nonce_field( 'review_box_meta_action', 'review_box_meta_nonce' );
10
?>
11
    <p>
12
        <label for="review_name">Movie Name:</label>
13
        <input type="text" name="_wptuts_review_name" id="review_name" value="<?php echo $_wptuts_review_name[0]; ?>" />
14
    </p>
15
    <p>
16
        <label for="review_year">Year:</label>
17
        <input type="text" name="_wptuts_review_year" id="review_year" value="<?php echo $_wptuts_review_year[0]; ?>" />
18
    </p>
19
    <p>
20
        <label for="review_director">Director:</label>
21
        <input type="text" name="_wptuts_review_director" id="review_director" value="<?php echo $_wptuts_review_director[0]; ?>" />
22
    </p>
23
    <p>
24
        <label for="review_writer">Writer:</label>
25
        <input type="text" name="_wptuts_review_writer" id="review_writer" value="<?php echo $_wptuts_review_writer[0]; ?>" />
26
    </p>
27
    <p>
28
        <label for="review_stars">Stars:</label>
29
        <input type="text" name="_wptuts_review_stars" id="review_stars" value="<?php echo $_wptuts_review_stars[0]; ?>" />
30
    </p>
31
    <p>
32
        <label for="review_genre">Genre:</label>
33
        <input type="text" name="_wptuts_review_genre" id="review_genre" value="<?php echo $_wptuts_review_genre[0]; ?>" />
34
    </p>
35
    <p>
36
        <label for="review_runtime">Runtime:</label>
37
        <input type="text" name="_wptuts_review_runtime" id="review_runtime" value="<?php echo $_wptuts_review_runtime[0]; ?>" />
38
    </p>
39
    <p>
40
        <label for="review_image">Image:</label>
41
        <input type="text" name="_wptuts_review_image" id="review_image" value="<?php echo $_wptuts_review_image[0]; ?>" />
42
    </p>
43
    <p>
44
        <label for="review_storyline">Storyline:</label>
45
        <textarea name="_wptuts_review_storyline" id="review_storyline" cols="30" rows="10"><?php echo $_wptuts_review_storyline[0]; ?></textarea>
46
    </p>
47
<?php
48
}
49
?>

Después, necesitamos crear la función que conseguirá que WordPress guarde los valores de entrada como campos personalizados:

1
2
function wptuts_review_box_save_meta( $post_id ) {
3
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
4
    if( !isset( $_POST['review_box_meta_nonce'] ) || !wp_verify_nonce( $_POST['review_box_meta_nonce'], 'review_box_meta_action' ) ) return;
5
    if( !current_user_can( 'edit_post' ) ) return;
6
    // create an array of our custom fields

7
    $review_array = array(
8
        '_wptuts_review_name',
9
        '_wptuts_review_year',
10
        '_wptuts_review_director',
11
        '_wptuts_review_writer',
12
        '_wptuts_review_stars',
13
        '_wptuts_review_genre',
14
        '_wptuts_review_runtime',
15
        '_wptuts_review_image',
16
        '_wptuts_review_storyline'
17
    );
18
	// create the "default" values for the array

19
    $review_array_defaults = array(
20
        '_wptuts_review_name' => 'None',
21
        '_wptuts_review_year' => 'None',
22
        '_wptuts_review_director' => 'None',
23
        '_wptuts_review_writer' => 'None',
24
        '_wptuts_review_stars' => 'None',
25
        '_wptuts_review_genre' => 'None',
26
        '_wptuts_review_runtime' => 'None',
27
        '_wptuts_review_image' => 'None',
28
        '_wptuts_review_storyline' => 'None'
29
    );
30
	// parse 'em!

31
	$review_array = wp_parse_args($review_array, $review_array_defaults);
32
    // HTML elements that are allowed inside the fields

33
    $allowed_html = array(
34
        'a' => array(
35
            'href' => array(),
36
            'title' => array()
37
        ),
38
        'em' => array(),
39
        'strong' => array()
40
    );
41
    // update the post meta fields with input fields (if they're set)

42
    foreach($review_array as $item) {
43
        if( isset( $_POST[$item] ) )
44
            update_post_meta( $post_id, $item, wp_kses($_POST[$item], $allowed_html) );
45
    }
46
}
47
add_action( 'save_post', 'wptuts_review_box_save_meta' );

¡Hecho!

Para saber más sobre cómo crear cajas meta personalizadas (y qué significan realmente estas líneas de código), puedes consultar este fantástico artículo de Christopher Davis publicado en Tuts+.

Paso 2 Crear la Función que Muestra la Sección de la Reseña

Ahora que ya hemos visto cómo configurar la información, tenemos que aprender cómo obtenerla. Si has trabajado con campos personalizados con anterioridad, esto te resultará sencillo, pues sólo vamos a extraer valores de campo personalizado.

WordPress tiene un función muy sencilla para obtener los valores de los campos personalizados:

1
2
$meta_values = get_post_meta($post_id, $key, $single);

Tenemos que cargar los valores de los campos personalizados dentro de código HTML, así que es buena empezar a pensar ahora en ese código. Estoy pensando en usar algo parecido a esto:

1
2
<div class="review-box">
3
	<img src="http://ourwebsite.com/uploads/the-pursuit-of-happyness.jpg" alt="The Pursuit of Happyness (2006)" class="review-box-image" />
4
	<ul class="review-box-list">
5
		<li><strong>Name:</strong> The Pursuit of Happyness</li>
6
		<li><strong>Year:</strong> 2006</li>
7
		<li><strong>Director:</strong> Gabriele Muccino</li>
8
		<li><strong>Writer:</strong> Steve Conrad</li>
9
		<li><strong>Stars:</strong> Will Smith, Jaden Smith, Thandie Newton</li>
10
		<li><strong>Genre:</strong> Biography, Drama</li>
11
		<li><strong>Runtime:</strong> 117 minutes</li>
12
		<li><strong>Storyline:</strong> Based on a true story about a man named Christopher Gardner. Gardner has invested heavily in a device known as a "Bone Density scanner". He feels like he has made these devices. However, they do not sell as they are marginally better than the current technology at a much higher price. As Gardner tries to figure out how to sell them, his wife leaves him, he loses his house, his bank account, and credit cards. Forced to live out in the streets with his son, Gardner is now desperate to find a steady job; he takes on a job as a stockbroker, but before he can receive pay, he needs to go through 6 months of training, and to sell his devices.</li>
13
	</ul>
14
</div>

Y si lo unimos todo, ¡ya tenemos nuestra función preparada!

1
2
function wptuts_review_box() {
3
    global $post;
4
    // get the custom field values as an array

5
    $values = get_post_custom( $post->ID );
6
    // extract the members of the $values array to their own variables (which you can see below, in the HTML code)

7
    extract( $values, EXTR_SKIP );
8
    // if there's no image link in the "review_image" custom field, try to get the featured image

9
    if($_wptuts_review_image == '') {
10
        if(has_post_thumbnail()) {
11
            $get_wptuts_review_image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
12
            $_wptuts_review_image = $get_wptuts_review_image[0];
13
        } else {
14
            $_wptuts_review_image = 'http://placehold.it/150x200&text=No+Image';
15
        }
16
    }
17
	// escape the output, just in case

18
	$allowed_html = array(
19
		'a' => array(
20
			'href' => array(),
21
			'title' => array()
22
		),
23
		'em' => array(),
24
		'strong' => array()
25
	);
26
	$_wptuts_review_name_output = wp_kses($_wptuts_review_name[0], $allowed_html);
27
	$_wptuts_review_year_output = wp_kses($_wptuts_review_year[0], $allowed_html);
28
	$_wptuts_review_director_output = wp_kses($_wptuts_review_director[0], $allowed_html);
29
	$_wptuts_review_writer_output = wp_kses($_wptuts_review_writer[0], $allowed_html);
30
	$_wptuts_review_stars_output = wp_kses($_wptuts_review_stars[0], $allowed_html);
31
	$_wptuts_review_genre_output = wp_kses($_wptuts_review_genre[0], $allowed_html);
32
	$_wptuts_review_runtime_output = wp_kses($_wptuts_review_runtime[0], $allowed_html);
33
	$_wptuts_review_storyline_output = wp_kses($_wptuts_review_storyline[0], $allowed_html);
34
	$_wptuts_review_image_output = wp_kses($_wptuts_review_image[0], $allowed_html);
35
    $output = '<div class="review-box">

36
        <img src="'.$_wptuts_review_image_output.'" alt="'.$_wptuts_review_name_output.' ('.$_wptuts_review_year_output.')" class="review-box-image" />

37
        <ul class="review-box-list">

38
            <li><strong>Name:</strong> '.$_wptuts_review_name_output.'</li>

39
            <li><strong>Year:</strong> '.$_wptuts_review_year_output.'</li>

40
            <li><strong>Director:</strong> '.$_wptuts_review_director_output.'</li>

41
            <li><strong>Writer:</strong> '.$_wptuts_review_writer_output.'</li>

42
            <li><strong>Stars:</strong> '.$_wptuts_review_stars_output.'</li>

43
            <li><strong>Genre:</strong> '.$_wptuts_review_genre_output.'</li>

44
            <li><strong>Runtime:</strong> '.$_wptuts_review_runtime_output.'</li>

45
            <li><strong>Storyline:</strong> '.$_wptuts_review_storyline_output.'</li>

46
        </ul>

47
    </div>';
48
    return $output;
49
}

El CSS

Evidentemente, puedes aplicar el estilo que más te guste a tu caja de reseñas. Pero si quieres, puedes usar los nuestros libremente:

1
2
.review-box {width:550px;border:1px solid #DDD;border-radius:5px;margin:10px;}
3
.review-box-image {float:right;width:150px;border:10px solid #fff;border-width:0 0 10px 10px;margin:10px 10px 0 0;}
4
.review-box-list {margin:10px;padding:0;list-style:none;}
5
.review-box-list li {margin-bottom:5px;padding-top:5px;border-top:1px solid #EEE;}
6
.review-box-list li:first-child {border-top:0;}
7
.review-box-list li strong {display:inline-block;width:75px;}
Si quieres flotar la caja de las reseñas hacia la izquierda o hacia la derecha, no olvides añadir la declaración float:left; (o float:right;) para .review-box. Podrías incluso centrarla cambiando la declaración margin:10px; por margin:10px auto;.

Paso 3 Crear el Shortcode para Replicar la Función

Ya sabemos cómo configurar la información, sabemos cómo obtener la información… ¡Es el momento de presentarla! :)

Siempre podemos añadir la sección al final (o al principio) de nuestro artículo automáticamente de la siguiente manera:

1
2
function wptuts_review_box_add($content) {
3
	$review_box = wptuts_review_box();
4
	// show the box at the end of the post:

5
	return $content.$review_box;
6
	// show the box at the beginning of the post:

7
	// return $review_box.$content;

8
} add_action('the_content','wptuts_review_box_add');

Pero, ¿qué pasa si queremos incluirla entre el contenido del artículo? Aquí es donde entra en juego mi parte favorita: ¡los shortcodes!

Este paso es incluso más sencillo que el anterior, debido a que ya hemos realizado todo el trabajo necesario para cargar la sección de la reseña. Todo lo que tenemos que hacer es invocar la función en forma de shortcode tal y como puedes ver aquí abajo:

1
2
add_shortcode('reviewbox','wptuts_review_box');

Aquí tienes lo que obtendrás si has seguido los pasos anteriores tal y como están escritos:

A screenshot of our example review boxA screenshot of our example review boxA screenshot of our example review box

Resumiendo

Estas cajas de reseñas podrían usarse para miles de tipos de valoraciones, como por ejemplo, reseñas de software, de sitios web, de libros, de programas de televisión, etc. O, si eres creativo, podrías incluso usarlas en blogs estándar, simplemente por diversión.

Algunos Artículos de Consulta

Para entender el código en su totalidad e incluso mejorarlo, te aconsejo la lectura de otros artículos de Tuts+.

¿Hay algo que que quieras mejorar o tienes alguna sugerencia? Comparte tus pensamientos con todos nosotros a través de un comentario.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.