0

When building custom themes, I often add my own functions inside functions.php:

<?php
    function my_function() {
            // Do something...
    }

Should I organize all my custom functions inside hooks?

<?php
    add_action( 'init','my_init' );
    function my_init() {
            function my_function() {
                    // Do something...
            }
    }
?>
  • 1
    You shouldn't nest functions like that, you should look up classes namespaces and object oriented code – Tom J Nowell May 15 '15 at 2:07
  • If I group my functions inside a class, how can I use them later with functions like add_action() or add_filter()? – Camilo May 15 '15 at 3:06
  • @Camilo replace 'function_name' with ['class_name', 'function_name'] – Nicholas Shanks May 15 '15 at 14:24
  • Thanks. Is there any documentation available about this? – Camilo May 16 '15 at 3:20
1

As @Tom J Nowell says, don't nest functions. Just write them normally:

function my_theme_prefix_setup() {
    // Add theme support etc.
}

add_action( 'after_setup_theme', 'my_theme_prefix_setup' );

function my_theme_prefix_init() {
    // Register a post type
}

add_action( 'init', 'my_theme_prefix_init' );

Or using a class:

class my_theme {
    function __construct() {
        add_action( 'after_setup_theme', array( $this, 'setup' ) );
        add_action( 'init',              array( $this, 'init' ) );
    }

    function setup() {

    }

    function init() {

    }
}

$my_theme = new my_theme;

Or using a "static" class (no instantiation) - since the class pattern in themes/plugins is often a glorified namespace, use them as such:

class my_theme {
    static function run() {
        add_action( 'after_setup_theme', array( __class__, 'setup' ) );
        add_action( 'init',              array( __class__, 'init' ) );
    }

    static function setup() {

    }

    static function init() {

    }
}

my_theme::run();

Then there's namespaces. So long as you're running PHP >= 5.3 (which you should be, though as @Nicholas mentions, you can't rely on for public themes - WordPress minimum requirements are only 5.2.4), this is the real solution that the above classes are attempting to resolve.

That said, there is no one right technique. Pick whichever suits the job, and that you're comfortable with. So long as you keep it clear, consistent and maintainable, you're doing it right.

  • 1
    If you're writing a theme or plugin for public consumption, you can't guarantee PHP 5.3+ – Nicholas Shanks May 15 '15 at 14:26
  • Thanks, I ended up organizing everything into classes without namespaces. – Camilo May 28 '15 at 1:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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