I’m trying to get my theme ready for publication on WordPress.org
I got this feedback:
function_exist() it is not preferable 3.0 design
Now I wonder what I’m doing wrong.
In the current structure I have:
functions.php
:
/* Load JBST functions on 'after_setup_theme'. */
add_action( 'after_setup_theme', 'jbst_theme_setup' );
if ( ! function_exists( 'jbst_theme_setup' ) ):
function jbst_theme_setup() {
/* Load custom Skematik header functions. */
require( get_template_directory() . '/functions/skematik-header-functions.php' );
//more code
}
/functions/skematik-header-functions.php
defines the function like:
add_action( 'skematik_header', 'skematik_doc_type', 9 );
function skematik_doc_type() {
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<?php
}
In this case skematik_doc_type
can be removed with remove_action
but can’t be overwritten, because it is not wrapped in a function_exists()
. Will this be the problem?
Do I have to wrap all functions in a function_exists()
and add them with add_action
? What are the rules for using function_exists()
or not?
Do not use
function_exists()
.Technically, your approach works. In practice, you create problems in your code without any benefit.
Readability. When someone else reads your code (e.g. you, one year later), the first question will be: why donât you know your own code? The second one is probably: OK, where is that function defined, how can I figure out which one is called?
Interoperability. When I want to replace your code, I am bound to your name.
skematik_doc_type()
is a poor name for a function that spits outdoctype
. I cannot replace it withskematik_doctype()
or a class method.Oh, and you cannot rename it either, because other peoples code might rely on that name.
Inconsistent behavior.
function_exists()
behaves not likedefined()
, you cannotreturn
from a file if the function returnstrue
, because all other code in that file will be parsed earlier. See the comments in the manual for examples. So you cannot reorganize your file structure later.Using
function_exists()
is a design decision as Chip pointed out. But a very bad one. It isnât forbidden in the theme review guidelines, but it should be. The WordPress core will not introduce more âpluggableâ functions for the reasons listed above.