How to reuse code in WordPress Page Template?

I have created a page template that is going to be used as homepage.
Homepage will contain three columns, each column will have excerpt of pages with particular meta_key value.

The code for this works but it is repeated each time for each column and only thing that differs is value of meta_key.

Read More

I am still new at this so I’m not sure what is a proper way to separate this code which contains both PHP and HTML?

  • by using PHP include statement?
  • by creating a function in functions.php which will contain that code?
  • by using WordPress get_template_part function?
  • Something else?

Related posts

Leave a Reply

1 comment

  1. In the end, what you want to use is what will be

    1. Easy to understand for someone else
    2. Convenient to you

    You’ve grasped the DRY – don’t repeat yourself – principle. This is very good. If you have to change something in the future, you don’t want to have to change the same thing in multiple places (it’s not convenient). So if you repeat the same thing in several different template files, you can use get_template_part. This function renders include() obsolete.

    You could stick your code into a function that takes the meta key as an argument. This would be a pretty neat solution. It would be very convenient. The problem is that if someone else reads this template they will not immediately know how that function looks, since it’s something custom that you made up, and they will have to find that function in order to figure it out.

    So perhaps your best bet is to use a foreach loop:

    foreach( array( 'meta_key1', 'meta_key2' ) as $key ) {
    // Your code
    }
    

    If the code is not too long and is mostly about displaying information not so much processing it, this could be a good solution. But this only works if the output you want to generate is adjacent. Otherwise you’re stuck with having to create a function, and in that case you should put it in functions.php.

    If the code does a lot of processing of information you should probably put it in functions.php. The template files are for displaying stuff, and should be readable by designers with only a little PHP experience.

    (btw it’s not wrong for functions to contain both PHP and HTML. All template tags essentially are such functions. WordPress does not encourage truly strict separation.)