I'm just starting out with WP and php, and building my first starter theme. When a wp function is wrapped in tags, where is wp calling these functions from? And what is the principle behind this?

There is endless info on the web about all of the functions, but being new to this I'm trying to get my head around the fundamentals of how it all works.

Any help / pointers would be amazing.



There are two separate pieces when you are calling a function:

  1. A function declaration. This is mandatory and can only happen once for each function name.
  2. A function call. You don't need to use a declared function, and if you do, you can call the same function multiple times.

Both parts must happen in a PHP context, i.e. in a part that starts with <?php and ends either with ?> or just with the end of the document. In other words: If there is no HTML after the opening PHP tag <?php you don't need to to close it. The end of the file is the same as ?>

An example: Let's declare a function in the theme's functions.php.

// function collection for the theme "WPSE Demo"

function html_wrap( $text, $tag )
    return "<$tag>$text</$tag>";

A functions.php never creates direct output, so we don't need a closing ?> in that file.

In a template file, we can now call that function multiple times:

echo html_wrap( 'Hello World!', 'h1' );
echo html_wrap( 'Here I am.', 'p' );

We need the PHP tags around these calls. Note that some theme authors are using PHP tags around every single function call in templates. They'd write the example above like this:

<?php echo html_wrap( 'Hello World!', 'h1' ); ?>
<?php echo html_wrap( 'Here I am.', 'p' ); ?>

Don't do that. It is harder to read and to change. It looks messy, and technically it is just redundant. Plain poor code style.

| improve this answer | |
  • A quick question. If in your function, I use apostrophes, this doesn't work but if I use the quotes, it does. I thought they were interchangeable. Why doesn't it work with apostrophes? – rudtek Mar 20 '17 at 17:08
  • @rudtek stackoverflow.com/questions/3446216/… – fuxia Mar 20 '17 at 17:09

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.