Avoid Duplication In WordPress Theme Code

When coding a WordPress theme, you might meet the situation when a section of code is duplicated across pages, for example the Loop is presented in all Index, Archive and Category pages. To avoid such code duplication, we can load a template part into a template file (other than header, sidebar, footer) to make it easy for a theme to reuse sections of code.

The WordPress Built-In Function

WordPress has a built-in function get_template_part for this purpose, but it is rarely used. This function has 2 parameters:

get_template_part($slug, $name)

– $slug: (required) The slug name for the generic template.
– $name: (optional) The name of the specialized template.

The function will include a template file called {slug}-{name}.php. If the theme contains no {slug}-{name}.php file then no template will be included.

Example Of Avoiding Duplicate Code

We’ll see an example of using the function get_template_part above to reuse the Loop code for index, archive and category pages.

Create a new PHP file in the theme folder, name it loop.php and paste all the code above into this file. And then, edit the index.php, archive.php, category.php, replace original Loop code with the following code:

Another Solution For Including Template File

You can use PHP built-in function include, require to load a template file instead of using WordPress get_template_part function, of course. But why do you do that if WordPress cares all for you? I don’t think this is a good idea, but we can mention it here as another possible method.

Avoid duplicated code in WordPress theme development helps programmers economize time and effort for writing code. This method described here also can help them make the code clearer and easier to maintain.