WordPress Theme Development single.php

Enhancing content in single.php with Custom Fields

Associated Files: single.php

This has been a technical challenge worth making some time for while I’m building the theme that goes with this subdomain. In this 4th post in this series, I want to talk about using Custom Fields. These are sometimes necessary when you need to make unique content that can’t be part of the main post. When I’ve finished talking about that, I’ll show how WordPress pagination methods are used in single.php templates.

I talked very briefly about using Custom Post Types and introducing these into the WordPress Core Post Types. It is possible to do this out of the box in WordPress, but they’re not Custom Post Types in that sense. 

Each blog post on this website has a section called has a part called “Associated files”. The idea of this is to give a quick list of the template files and programs that the blog post deals with.

 <div class="associated_files">Associated Files: MySQL, Local Dev Server (e.g. XAMPP), WordPress Files</div>

This, of course, presents a problem. Because the element is hard-coded into the template file, the text content will always be the same. That is unless we can find a way to display unique attributes for each blog post.

This is where Custom Fields come in.

Setting up Custom Fields

We need to do a bit of tweaking to set up the ability to use Custom Fields.

First, go into the editing mode on any one of your posts. This is for the core “Post” type.

Find the “Preferences” settings for your post. This is snuck away in the “options” tab. To find it look for the 3 vertical dots on the top right-hand side of your Post editing screen.

In the modal screen, scroll down to the “Advanced” area where you can toggle the ability to see Custom Fields. Now click on “Show and Reload the page”.

Custom Fields have 2 input boxes where you set up a name and a value for your custom field. This is usually below the content editor when writing or editing Posts.

By way of an example, I choose “associated_files” as a Name and a comma-separated list of files and programs as a value. This is one string value but it’s helpful to separate them with commas.

To apply the new custom setting click on the “Enter New” – You only need to do this once.

Now, update your post in the usual way. Click “Update”. This key-value pair should now be available to you whenever you need a new post and you can set different values for each Post you write.

Retrieve and display the key-value pairs

We’ve created the ability to use Custom Fields. I’ll show you now how to put them on the page. This is for the single.php template. This first example shows us the key and the set of values.

<div class="associated_files">Associated Files: 
    <?php foreach ( $mykey_values as $key => $value ) {
    
	      echo "$key => $value ( 'associated_files' )"; 
} ?> MySQL, Local Dev Server (e.g. XAMPP), WordPress Files</div>  

Inside the element, we’re writing a PHP foreach loop…… in $mykey we’re using get_post_custom_values and assigning it to $my_key and it is that method that stores the custom field information as a key-value pair so we are able to use it.

The foreach loop simply prints off the information one after the other. With no HTML formatting, they go side by side on the same line, which suits what I need in this case. 

It’s also tagged on a string at the end. Let’s clean that up a bit.

Below we simply display a list by displaying only the key values

<?php $mykey_values = get_post_custom_values( 'associated_files' ); ?>
    <div class="associated_files">Associated Files: 
    <?php foreach ( $mykey_values as $key => $value ) {
	      echo "$value"; 
    } ?>

Registering Custom Fields in Code

Support for all of this comes in WordPress out of the box without the need for writing code to do it. However, if you want to use that method you can place the following code in your functions.php file.

<?php
register_post_meta(

    'post', // Post type to register the meta for (in this case, 'post' for default posts)
    'associated_files', // Name of the meta key

    array(

        'type' => 'string', // Type of the meta value (string, integer, boolean, array, etc.)
        'single'=> false, // Whether the meta key has a single value or multiple values (false for multiple)
        'show_in_rest' => true, // Whether to expose the meta key in the REST API
        'sanitize_callback' => 'sanitize_text_field', // Optional sanitization callback function
        'auth_callback' => function() { 
            
            // Optional authentication callback function
                return current_user_can( 'edit_posts' );
            }
        )
    ); 

In this example:

We use the register_post_meta() function to register the custom field. The function takes the following parameters.

  • The first parameter specifies the post type to register the meta for, which is ‘post’ for default posts.
  • The second parameter is the name of the custom field, which is “associated_files” in this case.
  • We specify the type of the meta value as ‘string’ and allow multiple values ('single' => false).
  • We set 'show_in_rest' => true to expose the meta key in the WordPress REST API.
  • We can optionally define a sanitization callback function using the ‘sanitize_callback’ parameter to sanitize the input data.
  • We can also define an authentication callback function using the 'auth_callback' parameter to restrict access to the meta field.

After adding this code to your theme’s functions.php file or a custom plugin, you’ll see a new custom field named “Associated Files” in the post editor screen where you can enter the template files mentioned or used in a blog post.

Now we’re going to work on some blog pagination

Now we’re going to work on some blog pagination. I want to demonstrate 2 simple WordPress methods we can use to help us move to the previous and next blogs without moving away from the Single Post Template.

One or both of these output texts will be available, depending on which post you are on. The methods do not cycle infinitely, which means the “previous” post link does not display if you’re on the most recent blog post.

To counter this inconsistency in the design you could put these methods inside a HTML element that has a Flexbox container. 

<?php previous_post_link( '« Previous Page' ); ?>  // & laquo «

<?php next_post_link( 'Next Page »' ); ?> // & raquo »

We can now add these methods to our single.php template, anywhere that it seems necessary. In my example, I put it in a <nav> element. I also find it helpful to put a helpful link back to the home.php template.

<nav class="post_pagination_methods">

    <?php echo previous_post_link( '%link', '« Previous Post' ); ?>
    
    <a href="blog">Blog</a>
    
    <?php echo next_post_link( '%link', 'Next Post « >> ' ); ?>

</nav>  

Conclusion

That’s it for this section. This post has shown us a few more things you can do with single.php templates. There’s more that can be done with the.

Coming up in the next post, we’re going to work with post author tags, use the author template and talk about how to use custom page templates and why they’re sometimes necessary.