Advertisement
  1. Code
  2. Creative Coding

Utilizing Custom Fields to Create Review Boxes

Scroll to top
Read Time: 9 min

Reviews are perhaps one of the greatest powers of blogging in terms of authority. When done properly (with hard work and consistent information), review blogs are arguably the most profitable category in the blogosphere. But every blog has to offer a solid design in their posts, including reviews. In this post, we're going to talk about how to build the perfect review box, since review boxes are probably the first part readers check before reading a review.


What We're Going to Build

As an example, we're going to create a review box for a movie.

Let's take one of my favorite movies of all time, The Pursuit of Happyness. We're going to display the following information about the movie:

  • Name: The Pursuit of Happyness
  • Year: 2006
  • Director: Gabriele Muccino
  • Writer: Steve Conrad
  • Stars: Will Smith, Jaden Smith, Thandie Newton
  • Genre: Biography, Drama
  • Runtime: 117 minutes
  • Storyline: 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.
  • (Let's not forget that we need an image.)

Important: This information is borrowed from The Internet Movie Database.


Step 1 Preparing the Custom Meta Box to Fill in the Data

We're going to hold the data as custom field values, but adding custom fields manually for each review can be such a pain. Because of that, we're going to create a neat custom meta box to save our data as custom fields.

First, we need to use the add_meta_box() function to build the meta box and create a callback function:

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
}

The callback function will create the input fields to hold our data. I think we can use a texarea for the "storyline" field and text input fields for everything else:

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
?>

Then, we need to create the function to make WordPress save the input values as custom fields:

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' );

Done!

To find more information about creating custom meta boxes (and what these lines of code actually mean), you can read this fantastic article written by Christopher Davis and published on Wptuts+.

Step 2 Building the Function to Show the Review Box

Now that we covered how to set the information, we need to learn how to get the information. If you worked with custom fields before, this is going to be easy since we're just going to fetch custom field values.

WordPress has an easy-to-use function for getting custom field values:

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

We need to load custom field values into some HTML code, so it would be wise to think about the HTML now. I'm thinking something like this:

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>

And if we put them together, we'll have our function ready!

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
}

The CSS

Of course, you can style your review box any way you like. If you don't feel like it, you're welcome to use ours:

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;}
If you want to float the review box to left or right, don't forget to add the float:left; (or float:right;) declaration for .review-box. You can even center it by changing the margin:10px; declaration into margin:10px auto;.

Step 3 Creating the Shortcode to Echo the Function

We know how to set the info, we know how to get the info... Now it's time that we show the info! :)

We can always add the box automatically at the end (or at the beginning) of the post like this:

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');

But what if we want to include the box inside the post? That's where my favorite part comes in handy: shortcodes!

This step would be even easier than the previous one, since we actually done all the work to load the review box. All we have to do is call the function as a shortcode like this:

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

Here's what you'll have if you follow the steps above exactly as they're written:

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

Wrapping Up

These review boxes could be used for loads of different reviews like software, websites, books, TV shows and so on. Or, if you can get creative, you can even use them in regular blogs just to have fun!

Some Articles to Check

To fully understand the code and even to improve it, you should read some other articles of Wptuts+:

Is there anything you'd like to improve or do you have an idea? Share your thoughts with us by commenting below.

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.