Categories
WordPress Templates

WordPress Film Festival Site: Custom Fields for Single Post Views

If the conditional workout from the previous part of the exercise is confusing, remember that you could also have just made another template part to be called from the SINGLE.PHP template file.

But getting comfortable with conditions gives you a lot of power, so it’s definitely worth it to practice using them.

Anyway, in this part of the exercise, we need to conditionally add a bit more information for when we are in single view.

If you look in the screenshot of the single view of posts, you will see that some meta data is being output in single view. This meta-data is attached to each post with the ADVANCED CUSTOM FIELDS plugin, which is one of the most used plugins in the WordPress world.

If you look at one of the posts in the dashboard editing window, you will see the additional fields (for Country, Director, and Year).

If you edit a post, you will see the Advanced Custom Fields UI below the main content editing area.

WordPress has its own native custom fields, but the interface and functionality of the Advanced Custom Fields plugin is so superior that a large number of people choose to use the plugin over the native format.

Anyway, here’s a snippet that will add that content. Put it into content.php with a condition that outputs it only on single views of posts.

 
        <div class="entry-meta-data">
                <ul>
                    <li><b>Country: </b><?php esc_html(the_field('country')); ?></li>
                    <li><b>Director: </b><?php esc_html(the_field('director')); ?></li>
                    <li><b>Year: </b><?php esc_html(the_field('year')); ?></li>                   
                </ul>    
         </div>

To learn more about how to output data from Advanced Custom Fields, consult the developer’s Documentation.

You have likely noticed in this snippet that I have wrapped the ACF calls ( the_field() ) inside the WordPress esc_html() function. This function, and others that are similar, is used throughout underscores. This is called SANITIZING.

The reason for using it is that if either malicious code ( small example: <script>alert(‘this site sucks!’)</script> ) or badly formed HTML is entered into a field, it can have embarrassing (or worse) consequences.

A couple tests make me suspect that ACF sanitizes user input anyway, but it is never a bad idea to sanitize on output as well as input.

Anyway, with some styling, the page looks like this (click image for larger, detailed, view, or consult the downloaded screenshots):

Please style it to look like that (ignore the CLICK to REGISTER button in the footer of the screenshot for now: we haven’t put it in yet).

Then move on to the next discussion, on using do_shortcode() to inject plugin output into template files.