Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 4 • WordPress Theme Essentials 101


Putting Page templates to good use is a huge step toward creating the site you want using
WordPress.


USING FUNCTIONS.PHP


One theme file you haven’t touched very much yet is functions.php. It is a bit mysterious, and
most people take a brief look at it and then shy away. Not all themes have functions.php files,
but the ones that do usually support widgets and may even have their own options page inside
the WordPress admin. This is possible thanks to the functions.php file.


What, then, does functions.php do? Basically, it does whatever you want it to because it more
or less acts like a plugin that is called within the WordPress initialization, both when viewing
the public site and when loading the admin interface. Because of that, you can add admin
functionality to functions.php.


You’ll look at widgets and how to set up widget areas later, but first, add a simple function to
functions.php:


<?php
function hellomate() {
echo 'Hello mate, how are you doing?';
}
?>


If you put that simple little code snippet in functions.php and then call the function somewhere
within your theme, it will output the “Hello mate, how are you doing?” text. You call the
function as you would call any PHP function:


<?php hellomate(); ?>


So that would echo the text. Not very useful, perhaps, but it does show you something that
functions.php can do. If you have code snippets you use all the time and want them easily
accessible, this is your solution.


Many themes use admin options pages to let the user set his or her own color schemes or
font styles, or perhaps change the header. This is all managed with functions.php. You’ll
dive further into functions.php in Chapter 6 and onward.


SETTING THE DEFAULT WIDTH


A commonly forgotten feature is the content width setting. Content width, which is a simple
little snippet added to functions.php, tells WordPress the maximum width that the theme can
manage, which in turns means that the theme will resize images accordingly. Sure, you have
Media Settings in the WordPress admin interface, where you can control the size of images
(see Figure 4-9), but the user may forget to change these things when changing themes.

Free download pdf