1

I’m building a theme, and I’m using an oop approach, nevertheless all themes source code that I have seen until now, make use of procedural approach, so they write this sort of code:

If ( ! function_exists( ‘my_theme_function’ ) ) { 
  my_theme_function() {
    // code function here
  }
}

So what is the ideal methodology to use on my functions.php ? is even oop considered a bad practice on this context ? Thank you..!!

1
  • You can do whatever you want in functions.php, doing OOP stuff isn't wrong
    – Tom J Nowell
    Mar 14, 2017 at 19:26

1 Answer 1

3

As described in the Child Themes entry in the codex:

TIP FOR THEME DEVELOPERS. The fact that a child theme’s functions.php is loaded first means that you can make the user functions of your theme pluggable —that is, replaceable by a child theme— by declaring them conditionally.

if ( ! function_exists( 'theme_special_nav' ) ) {
function theme_special_nav() {
    //  Do something.
    }
}

In that way, a child theme can replace a PHP function of the parent by simply declaring it beforehand.

If the theme you are developing will be released for general usage (i.e., you will be submitting it to the wordpress.org repository), then you should definitely build in capabilities that allow others who are building child themes based on your theme to override certain features of your theme.

Which features you allow to be override is up to you, and you need not build in the capability to override every function/feature.

Another thing you can do to make it easier for others to build child themes from your theme is to incorporate theme-specific actions/filters where appropriate.

As to your OOP vs procedural question: it really comes down to personal style.

To build an OOP style theme, you can make judicious use of final methods. That is, when a procedural style should not wrap a function in if (!function_exists(...)) { then you'd make that method final, etc.

Edit

The answer to this other WPSE question provides more context for developing OOP style themes.

1
  • Thanks a lot @Paul 'Sparrow Hawk' Biron, that was very clear..!!
    – Roberto
    Mar 14, 2017 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.