An Introduction to Functions.php in WordPress

An Introduction to Functions.php in WordPress

If you’re an aspiring WordPress developer, one of the most important files you need to master is the functions.php file.

If you’re developing or modifying a theme, you need to know how to get the most out your functions.php file.

We’re going to show you 10 examples of common functions you can add with just a little code.

Introducing the functions.php file

tutuploadsmedia_1336691010658_f605698d1fa26c76c5620ede1645a30b.png

Your functions.php file will be /wp-content/themes/your_theme_name/functions.php

The best choice for modifying existing themes is to use a child theme. This way when you upgrade your theme your changes won’t be overwritten. See this tutorial on creating a child theme if you need help: http://www.ostraining.com/blog/wordpress/child-theme/

Note: There is also a functions.php file in the wp-includes folder. Don’t use that one unless you are an expert coder.

Our recommendation is that you paste all your new code into the very bottom of your funcations.php file. Here’s how to do it:

  • Open the functions.php file in a script editor.
  • Scroll to the bottom.
  • Find the last line.
  • Paste the snippet after that last line.
  • Save the file.
tutuploadsmedia_1337285401705.png

Example 1: Google Analytics

tutuploadsmedia_1337285268007.png

Pasting this in your functions php will add the code to all your page where you have the footer.

The first line add_action(‘wp_footer’, ‘add_googleanalytics’); specifies that i will add google analytics anywhere the footer is used. That’s called a “hook”. To use this, get your google analytics code from google and replace the entire line “// Paste your Google Analytics code here” with your actual code from Google. Be sure you remove the // comment marks.

<?php
add_action('wp_footer', 'add_googleanalytics');
function add_googleanalytics() { ?>
// Paste your Google Analytics code here
<?php } ?>

Example 2: Adding an Excerpt Box on Pages

tutuploadsmedia_1337285426962.png

The WordPress Excerpt is an optional summary or description of a post; in short, a post summary. The Excerpt has two main uses: It replaces the full content in RSS feeds when the option to display summaries is selected in Dashboard › Settings › Reading. Depending on the WordPress theme, it can be displayed in places where quick summaries are preferable to full content: like Search results, Tag archives, Category archives, Monthly archives, and Author archives

But it’s only available with the standard template on posts, not pages. Excerpts on WordPress pages used to be a standard feature, then it disappeared. But luckily they made it easy to put the excerpt window back into the Add New Page editor with a single line of code.

The snippet:

add_post_type_support( 'page', 'excerpt' );

You’ll see the excerpt box on the editing page. (If it’s not visible, Check the Screen Options and see if the correct checkbox is checked.)

Example 3: Remove the WordPress Version Number

tutuploadsmedia_1337290638631.png

The version generator makes the version of wordpress you are using available by simply viewing the page code. If you must use an older version of WordPress for some reason, this may present a security risk. The best protection is to always run the most current version. Some people suggest it isn’t necessary to remove the version number because there are other ways for hackers to find out what you’re running. Others recommend that you always do it. If you are going to do it, here’s the correct way, using your functions.php file.

function i_want_no_generators()
{
return '';
}
add_filter('the_generator','i_want_no_generators');
tutuploadsmedia_1337290759522.png

The version is no longer generated and doesn’t appear in the code view.

Example 4: Add a Favicon to Your Theme

tutuploadsmedia_1337291305748.png

Lots of people want to brand their sites with special favicons. It really lends a professional and finished look to a theme. First you’ll have to create the icon. You can use one of the many free icon generators on the web. Just google “icon generator” and you’ll find a good one. Then upload a copy of the icon to the main WordPress directory, and one to your theme’s directory. Add the code to functions.php and you’re good to go.

function blog_favicon() {
echo '';
}
add_action('wp_head', 'blog_favicon');

Example 5: Always Updated Copyright Dates

tutuploadsmedia_1337294458098.png

Above is a typical copyright notice. Usually people put the copyright somewhere in the footer, and its basically a static date, or could be a dynamic date showing just one year. But there’s a way to make it more accurate and cover your entire career as a publisher. This function call will get the date of the first post and the date of the last post so you can publish them.

Working it into your functions.php file is just a little more difficult because you actually have to know how to write the function and it’s a bit more complicated than our previous examples. Notice that you can name the function you create anything you want as long as it doesn’t conflict with any other functions.

function copyright_function_of_mine() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
post_status = 'publish'
");
$output = '';
if($copyright_dates) {
$copyright = "© " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
}
$output = $copyright;
}
return $output;
}

After you get this into your functions.php file, you just need to add this code to your footer.php or wherever you want the dates to show up.

<?php echo copyright_function_of_mine(); ?>
tutuploadsmedia_1337293791509.png

This is what I added to my footer.php file. You can add text and html or css to the footer to add style.

tutuploadsmedia_1337293738403.png

Here’s what it looks like on the site. It shows the year of my first post and my last. The copyright is completely up to date.

Example 6: Turn on Post Thumbnails

tutuploadsmedia_1337300268164.png

Post thumbnails are a function of wordpress. But you need to let your theme know that you want to use the feature. Here’s how you turn on the post thumbnails. It’s very easy to add the function to the template. It becomes more complex when it comes to styling the pictures, though. We’re only covering the functions.php file in this tutorial. We’re just going to show you the first step.

First you activate the function with this line in functions.php

add_theme_support( 'post-thumbnails' );

Now, just like with the copyright example, you have to put some code into the site somewhere that will call the results of the function and display it. With the copyright example we placed the function call in the footer. With this, since it’s something that is dynamically associated with each post, it goes in the Loop. You just need to add this one line to the Loop put the picture where you want it.

get_the_post_thumbnail($id, $size, $attr )

The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post. When WordPress documentation states “This tag must be within The Loop”, such as for specific template tags or plugins, the tag will be repeated for each post. You can learn more about the Loop in the Codex.

The Loop is found inside the templates index.php file. You would need to place this code between the start and end of the post loop. The loop starts with:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

and ends with:

<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

You’d place your code anywhere between those two lines that doesn’t interfere with any other code.

This will get the picture into the post. The terms $id, $size, and $attr will dictate how it displays and what it looks like. This involves creating arrays and some more advanced programming which is more advanced than we want to get with this introduction. Here’s a complete reference to post thumbnails in the Codex.

Be sure to take our PHP, HTML, and CSS courses first if you don’t have much experience with this. You will learn everything you need in those courses. Also watch for our soon to be released WordPress Theming course, which we will announce in our newsletter and on our site.

Example 7: Add Support for Custom Post Formats

tutuploadsmedia_1337301989977.png

Something not often understood in WordPress is the difference between Post Formats and Post Types. There are 9 post formats built into WordPress, and you may even see them listed on your post edit page. But before they will be active in your theme, you need to add support for them in the functions.php file. If you want a complete explanation of post formats, read our tutorial How to Activate WordPress Post Formats.

add_theme_support('post-formats', array( 'aside', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video', 'audio'));

You won’t be able to use post formats without this line in functions.php.

Example 8: Enable Threaded Comments in Your Theme

tutuploadsmedia_1337307417180.png

You can turn on threaded comments from your WordPress control panel. But when you are developing themes, you still have to write the java script in the header.php file. To avoid clutter in your header file, use functions.php instead. If you are creating several themes, think how much easier it will be to have functions enabled from a single, reproducible functions file than to have to write extra code in header files and keep track of them all.

You will know if you are using threaded comments if you see a “Reply” link in each post.

// enable threaded comments
function enable_threaded_comments(){
if (!is_admin()) {
if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1))
wp_enqueue_script('comment-reply');
}
}
add_action('get_header', 'enable_threaded_comments');

This may seem unnecessary when you are using a well known theme because it’s already enabled in most. But if your starting from scratch, you have to make sure it’s included.

Example 9: Create Shortcode for Adsense

tutuploadsmedia_1337306212933.png

I inserted the adsense banner in the above illustration with a single short code. All I had to do was type [adsense] into my article. You can use functions.php to create your own shortcodes. Just paste the following code into functions.php and replace the specifics with your own Adsense numbers.

function showads() {
return '<div id="adsense"><script type="text/javascript"><!–
google_ad_client = "pub-XXXXXXXXXXXXXX";
google_ad_slot = "4668915978";
google_ad_width = 468;
google_ad_height = 60;
//–>
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js";>
</script></div>';
}
add_shortcode('adsense', 'showads');

Example 10: Enable a PayPal Donation Short Code

tutuploadsmedia_1337308172644.png

There are probably a lot of times you or your clients want to drop a donation button into a post or article. Pretty easy with this code Just put in your own account info. Just use [donate shortcode] to insert the donation link. This example is a little different because it includes the link text which actually shows on the post.

function donate_shortcode( $atts ) {
extract(shortcode_atts(array(
'text' => 'Make a donation',
'account' => 'REPLACE ME',
'for' => '',
), $atts));

global $post;

if (!$for) $for = str_replace(” “,” “,$post->post_title);

return ‘‘.$text.’‘;

}
add_shortcode(‘donate’, ‘donate_shortcode’);

Example 11: Style Odd and Even Posts with Alternate Styles

tutuploadsmedia_1337311950364.png

As a design element it’s often desirable to create different styling for every other post. suppose you wanted to alternate gray and white backgrounds. Or possibly switch the thumbnail image from left to right on alternate posts. There would be two things to do. One is create the function. The second would be to create a different css class for each, one called odd, and one called even.

You can see in the illustration that each post class now contains the words odd and even.

function oddeven_post_class ( $classes ) {
global $current_class;
$classes[] = $current_class;
$current_class = ($current_class == 'odd') ? 'even' : 'odd';
return $classes;
}
add_filter ( 'post_class' , 'oddeven_post_class' );
global $current_class;
$current_class = 'odd';

All that remains is for you to use your design skills and css knowledge to make it beautiful.

This was just a short intro to the power of the functions.php file. It doesn’t stop here. If you are planning on developing and designing your own themes, you need to get familiar with this file, creating functions using php, and mastering css. If you don’t get serious about it, there is a probably a plugin that does the same thing. That’s the beauty of WordPress.

Author

0 0 votes
Article Rating
Subscribe
Notify of
6 Comments
Oldest
Newest
Inline Feedbacks
View all comments
brij
brij
11 years ago

Exillent tutorial

Ruben Grimm
Ruben Grimm
10 years ago

Regarding Example 11: Nowadays you should use the nth-child CSS-function for that.
[url=https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child]https://developer.mozilla.o…[/url]

Jatin Gadhiya
Jatin Gadhiya
10 years ago

very nice tutorial

php submission
php submission
9 years ago

Thanks for sharing this information…

[url=https://www.imeshlab.com/PHP.IM]Php training in chandigarh[/url]

web design courses
web design courses
8 years ago

Thanks for sharing these valuable points.Looking forward to hear more from you

sergei
sergei
4 years ago

thanks
You are great man.

6
0
Would love your thoughts, please comment.x
()
x