When is it appropriate to put functions on page template vs. functions.php?

I’d like to improve my code and on a current theme, I’ve extended WordPress with custom post types, metadata, customized user authentication, and a number of other items.

Some of these functions exist in the functions.php file while I’ve put others directly on the template files that they relate to. I have little reason for doing this initially, other than it seemed appropriate because said template file was the only file using the specific function.

Read More

But I’d like to know what is considered best practice for the sake of speed and security? What do you do?

Related posts

2 comments

  1. If it is a custom theme for your site then there would no great speed or security improvements by moving functions.

    On the other hand if you want to distribute the theme then I recommend having only the minimum php in the page templates files and having the rest of the functions organized in different files. I like the basic theme set up files of the theme to be in the functions.php and the rest in separate organized files. _s does a good job of this. The reason for moving the functions away from the templates files is that it makes it easier to customize and manage. If you need to duplicate a template then you do not end up duplicating functionality.

    I would even place the non-presentational functions in a plugin for easy deactivation and management. See this answer for more information.

  2. Clearly, if you update your parent theme, any template changes will be lost.

    The reason its better to use a child themes functions.php file is so your custom coding is safe when you update your parent theme.

    You should never modify any of the files in your parent theme and always use a child theme or create a plugin which you can add custom coding to.

    Using WordPress/theme specific filters to modify the output of existing parent theme and WordPress functions is best practice.

    You can also use theme specific/WordPress action hooks to add more functionality and content via your child themes functions file.

    On top of this, you can simply add templates to your child theme or copy them over from your parent theme and make the changes to them in your child theme. Really, it means the user doesn’t fully understand how to use hooks and filters and looking for the easy solution.

Comments are closed.