Reduce Code Duplication Using Functions

Since the banner image and description custom fields are used on all post types, we need to edit the banner area code in all template files to display the custom field values. Instead of duplicating the code, we can create a function in functions.php. This way, we will only write the logic once and simply call the function in all template files created so far.

Also, in case there is a change in the banner area code, we will not have to fix it in multiple template files.

Creating a function

Open single-teacher.php file where we added code to display custom field values in the previous lesson. Copy the HTML code for the banner area that is responsible for displaying the banner image, title, and description.

Open functions.php and create a method called display_page_banner. We will paste the copied HTML code in this method. Remember to close out the PHP mode before pasting HTML code and re-enter PHP mode before the closing function brace.

Get hands-on with 1400+ tech skills courses.