...

/

Reduce Code Duplication Using Functions

Reduce Code Duplication Using Functions

Learn to use functions to reduce duplicate code.

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.

<?php
function display_page_banner() { ?>
<!-- paste HTML code for page banner here -->
<?php
}
display_page_banner function

Back in single-teacher.php, we can call the function in place of the banner area code to make sure that everything is working as desired. The function is called while we are still in PHP mode.

<?php
while(have_posts()){
the_post();
display_page_banner();
?>
<div class="container">
<!-- Post content-->
<div class="generic-content">
<p><?php the_content() ?></p>
</div>
</div>
<?php
}
Calling the display_page_banner function

Save changes and confirm the banner is being displayed correctly on the teacher posts.

On page.php, which powers pages like About Us, we can also delete the HTML code for the page banner <div> and in its place call the display_page_banner() function like we did in single-teacher.php. If we view the About Us page, we can see the description from the custom ...