August 20, 2022

Building a WordPress Custom Post Template with Custom Data Fields

After creating the basic WordPress site, I wanted to create a separate template for Classic Movies Worth Your Time. As I learned when I was creating a custom theme, a custom template is mainly an exercise in PHP, HTML, and CSS.

Custom Post Template

Create a PHP file - post-classic-movies.php. The file's name is not important, but make sure to use the following metadata at the top of the file.

<?php
/*
 * Template Name: Classic Movies template
 * Template Post Type: post
 */
get_header('inner', array('titleAppend' => 'Classic Movies Worth Your Time'));
?>

The metadata is, so WordPress knows to use this file as a post template. The remainder of the PHP file is standard HTML, CSS, JS, and PHP as needed.

Once the WordPress platform picks up the template, the post editor will display the template as an option.

Custom Data Fields

Once the post template was done, I needed the ability to access a few custom data fields. In my specific case, two fields - secondary-image and front-page-card-header-text. These two values are entered when creating a new post and read by the template.

Because my template required an image outside of the normal blog post content area, I need to pass in the imagery using custom data fields.

Below code snippet is how to access the custom values in PHP.

The following snippet of PHP is how you can retrieve the custom value within a template.

<?php
    echo get_post_custom_values('secondary-image')[0];
?>

Result

Final result - post template and custom data field (image / movie poster)

Using a combination of Templates and Custom Data Fields, was able to get (1) a custom header, (2) the normal blog post body showing up in the content area, and (3) an image, the movie poster, showing up elsewhere in the page.

FILED UNDER:  WordPress
RELATED POST TO READ

How to Deploy WordPress with SSL on Google Cloud for Free

In a few hours, anyone, even those not well-versed in cloud computing or shell scripting, can deploy WordPress running SSL for free in Google Cloud.

RELATED POST TO READ

How To Redirect to HTTPS for WordPress with NGINX and SSL Certified by Bitnami and Automattic

How to redirect HTTP (unsecured) traffic to HTTPS when using NGINX.

RELATED POST TO READ