Skip to content

Overloading functions in WordPress child themes

I was doing a quick freelance WordPress development job for a publishing company based in Cheltenham today, having to modify an existing theme to better fit their design goals. Because the theme was quite complex and included a large amount of custom functionality, I didn’t want to start hacking the core theme files. So I need to create a sub-theme.

Creating sub-themes is a trivial task. The problem comes when you need to override some of the functions used in the parent theme. The difficulty is that you cannot redeclare a function in PHP without it throwing a fatal error. Plus you can’t overload functions or methods by creating a new method signature, as you could in C#. So how do you solve the problem?

If the theme is exceptionally well designed, all of the parent theme function will be wrapped in a function_exists() call. Due to the order that WordPress loads theme files, it will first load the child theme function, then attempt to load the parent theme function. If a parent theme function is declared as shown below, you can happily redeclare the function in your child theme safe in the knowledge you won’t get fatal errors.

if ( ! function_exists( 'theme_function' ) ) {
    function theme_function() {
   // Do clever stuff here
    }

If they haven’t wrapped their functions, you need to hope that the function you wish to override has been added to one of WordPress many hooks, or that the theme has it’s own method of locating and loading functions in the child theme ( as Thematic does). If not, you’re going to have to do some ugly hacks, or risk your changes getting over-written when the client updates the theme.

Looking for a web developer to turn your web designs into reality? Sweet-Apple develops websites for small businesses, design agencies and freelance designers, quickly, efficiently and cost-effectively. Why not give us a call on 01380 830224 and find out how we can help…

This entry was posted in Web Development, Wordpress and tagged , , , . Bookmark the permalink.

Comments

Sorry, comments are closed on this page.