Vous êtes sur la page 1sur 19

25+ Extremely Useful Tricks for the WordPress

Functions File

Last updated on January 4th, 2013 by Editorial Staff

SHARE THIS ARTICLE

In your WordPress theme folder, there lays the most powerful theme file known asfunctions.php. As the name

suggests, this file adds unique functions to your WordPress installation. This file works just like a plugin

within your theme. So you can modify/override WordPress core features without editing any core file. If used

correctly, this file can do wonders for your WordPress site. It also speeds up development because you can

have all the codes at one place. In this article, we will share some of the most incredible and most wanted

tricks for the WordPress functions.php file.


Note: This article is targeted for WordPress theme developers. You may need have some PHP knowledge for

some hacks.

Duh Moments: All codes in this article will be added to the functions.php theme file.

1. Add Google Analytics

Simply paste the code below and insert your Google Analytics where it says paste your Google Analytics. You

can paste the code once in your functions.php file and never have to worry about it again. We are adding an

action to the wp_footer, so it will automatically insert adsense codes wherever on all pages you have the

wp_footer string.
1 <?php
2 add_action('wp_footer', 'add_googleanalytics');
3 function add_googleanalytics() { ?>
4 // Paste your Google Analytics code from Step 6 here
5 <?php } ?>

For more details: Beginner’s Guide to Installing Google Analytics in WordPress

2. Add a Favicon to your Blog

Every blog deserves to have its own identity. You can add this identity by adding the favicon code in your

header.php file, or you can make it easier for yourself by simply adding the following code in your

functions.php file.
1 // add a favicon to your
2 function blog_favicon() {

3 echo '<link rel="Shortcut Icon" type="image/x-icon"


href="'.get_bloginfo('wpurl').'http://cdn3.wpbeginner.com/favicon.ico" />';
4}
5 add_action('wp_head', 'blog_favicon');

Now whenever you are developing the theme, just upload the .ico file in the root folder where the blog is

uploaded. You can also modify the file destination if you like. Often theme developers forget to change the

URL of the favicon. This can eliminate another worry.

Source: Digging into WordPress

3. Remove WordPress Version Number


You should always encourage your clients to upgrade to the latest version, so you don’t have this problem. But

if you are working with a client that does not want to upgrade, then it is essential that you remove your

WordPress version number from your WordPress header, RSS feeds, and all other locations. To do this, add

the following code:


1 function wpbeginner_remove_version() {
2 return '';
3}
4 add_filter('the_generator', 'wpbeginner_remove_version');

Source: The Right Way to Remove WordPress Version Number

4. Add a Custom Dashboard Logo

When creating themes for a client, you can use this as one of the perks to the theme. All you have to do is paste

the following code below:


01 //hook the administrative header output
02 add_action('admin_head', 'my_custom_logo');
03
04 function my_custom_logo() {
05 echo '
06 <style type="text/css">
#header-logo { background-image:
07 url('.get_bloginfo('template_directory').'/images/custom-logo.gif)
!important; }
08 </style>
09 ';
10 }

Screenshot:

Source: Jacob Goldman’s Article on Smashing Magazine


5. Change the Footer in WordPress Admin Panel

You can change the footer of your Free or Custom WordPress themes by adding the necessary links. Simply

paste the following code:


1 function remove_footer_admin () {
echo 'Fueled by <a href="http://www.wordpress.org"
2 target="_blank">WordPress</a> | Designed by <a href="http://www.uzzz.net"
target="_blank">Uzzz Productions</a> | WordPress Tutorials: <a
href="http://www.wpbeginner.com" target="_blank">WPBeginner</a></p>';
3}
4
5 add_filter('admin_footer_text', 'remove_footer_admin');

Screenshot:

Source: WPRecipes

6. Add Custom Dashboard Widgets in WordPress

You probably have seen widgets that numerous plugins and themes add in the WordPress dashboard. As a

theme developer, you can add one yourself by pasting the following codes:
01 add_action('wp_dashboard_setup','my_custom_dashboard_widgets');
02
03 function my_custom_dashboard_widgets() {
04 global $wp_meta_boxes;
05
wp_add_dashboard_widget('custom_help_widget', 'Theme
06
Support','custom_dashboard_help');
07 }
08
09 function custom_dashboard_help() {
echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a
10 href="mailto:yourusername@gmail.com">here</a>. For WordPress Tutorials
visit: <a href="http://www.wpbeginner.com"
target="_blank">WPBeginner</a></p>';
11 }

Remember to change the email and add any other information you want. Result would look something like

this:
Source: Jake Goldman’s Article at Smashing Magazine

7. Change the Default Gravatar in WordPress

Have you seen the default Mystery man avatar on blogs? Why waste the branding opportunity for your clients?

You can replace the mystery man with a custom branded gravatar for your clients to give their site a unique

touch. All you have to do is paste the following codes:


1 add_filter( 'avatar_defaults', 'newgravatar' );
2
3 function newgravatar ($avatar_defaults) {
4 $myavatar = get_bloginfo('template_directory') .'/images/gravatar.gif';
5 $avatar_defaults[$myavatar] = "WPBeginner";
6 return $avatar_defaults;
7}

Don’t forget to upload a custom image to your theme’s image folder. Also change the name of the gravatar to

their brand name. Once you upload the image and the functions, then visit: WP-Admin » Settings » Discussion
Your gravatar will show up as one of the options.

Source: How to Change the Default Gravatar in WordPress

8. Dynamic Copyright Date in WordPress Footer

Often you will come across sites with outdated copyright dates. Some sites show the current year as their

copyright date. Both of these are annoying, and it shows that the site designer was lazy. In order to give your

users a little background info about your site, you should display the copyright date as such: © 2006 – 2010.

We can do this by simply pasting the following code:


01 function comicpress_copyright() {
02 global $wpdb;
03 $copyright_dates = $wpdb->get_results("
04 SELECT
05 YEAR(min(post_date_gmt)) AS firstdate,
06 YEAR(max(post_date_gmt)) AS lastdate
07 FROM
08 $wpdb->posts
09 WHERE
10 post_status = 'publish'
11 ");
12 $output = '';
13 if($copyright_dates) {
14 $copyright = "&copy; " . $copyright_dates[0]->firstdate;
15 if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
16 $copyright .= '-' . $copyright_dates[0]->lastdate;
17 }
18 $output = $copyright;
19 }
20 return $output;
21 }

Once you add this function, then open your footer.php file and add the following code wherever you like to

display the dynamic copyright date:


1 <?php echo comicpress_copyright(); ?>

This function looks for the date of your first post, and the date of your last post. It then echos the years

wherever you call the function.


Source: @frumph of ComicPress Theme (How to Add a Dynamic Copyright Date in WordPress)

9. Rewrite Guest Author’s Name with Custom Fields

Now many blogs are publishing other authors also known as guest authors. A lot of these guest authors are one

time writers. In this scenario, it is not feasible to create user accounts for them. This trick will let you replace

the author name to guest author with the use of a custom field. Simply paste the code below:
01 add_filter( 'the_author', 'guest_author_name' );
02 add_filter( 'get_the_author_display_name', 'guest_author_name');
03
04 function guest_author_name( $name ) {
05 global $post;
06
07 $author = get_post_meta( $post->ID, 'guest-author', true );
08
09 if ( $author )
10 $name = $author;
11
12 return $name;
13 }

Now every time there is a guest post, simply add the custom field guest-author.

Source: Guest Authors in WordPress

10. Enable Post Thumbnails in WordPress


Starting from WordPress 2.9, you can use the default built-in Thumbnails feature in your themes. To do this,

you must enable the post thumbnails inside your functions.php file. Paste the code below:
1 add_theme_support( 'post-thumbnails' );

Then simply place the following code inside your loop where you want to display the thumbnail:
1 <?php the_post_thumbnail(); ?>

You can follow the Video Tutorial here:

Source: How to Add Post Thumbnails in WordPress

11. Custom Navigation Menus in WordPress 3.0

WordPress 3.0 comes with an awesome menu management system which theme developers can utilize to their

advantage. If you want to give your users the option to use this core feature, then add the following function:
1 add_theme_support( 'menus' );

Then you can call this function anywhere you like in your template file by pasting the code below:
<?php
1 wp_nav_menu( array( 'sort_column' => 'menu_order','container_class' => 'menu
-header' ) ); ?>

Additional Resource: WordPress Codex

12. Remove Default Author Profile Fields in WordPress

If you are creating a site where your client will be adding user information, then make the interface easier for

them. One of the ways you can do this is by removing the unwanted fields such as AIM, Yahoo IM, Jabber etc.

Simply paste the following code to remove these fields:


1 add_filter('user_contactmethods','hide_profile_fields',10,1);
2
3 function hide_profile_fields( $contactmethods ) {
4 unset($contactmethods['aim']);
5 unset($contactmethods['jabber']);
6 unset($contactmethods['yim']);
7 return $contactmethods;
8}

Source: Strangework

13. Add Author Profile Fields


If you want to create a more versatile author page, then you would need to add additional fields to the author

profile. The code below will show you how to add additional twitter and facebook fields, but you can use it to

add any other field that you like.


1 function my_new_contactmethods( $contactmethods ) {
2 // Add Twitter
3 $contactmethods['twitter'] = 'Twitter';
4 //add Facebook
5 $contactmethods['facebook'] = 'Facebook';
6
7 return $contactmethods;
8}
9 add_filter('user_contactmethods','my_new_contactmethods',10,1);

The function above will add something like this:

You can then call the fields in your author.php template by adding the following code:
1 <?php echo $curauth->twitter; ?>

** This tutorial will work only with versions 2.9+

Source: Yoast

14. Register Sidebar Widgets

This is one of the most used ones and many developers already know about this. But it deserves to be in this

list for those who don’t know. Paste the following code in your functions.php file:
01 if ( function_exists('register_sidebar') )
02 register_sidebar(array('name'=>'MiddleSidebar',
03 'before_widget' => '<li class="widget">',
04 'after_widget' => '</li>',
05 'before_title' => '<h2 class="widgettitle">',
06 'after_title' => '</h3>',
07 ));
08 register_sidebar(array('name'=>'FooterSidebar',
09 'before_widget' => '<li class="widget">',
10 'after_widget' => '</li>',
11 'before_title' => '<h2 class="widgettitle">',
12 'after_title' => '</h3>',
13 ));

The code above will register two sidebars. You can register as many as you need. To display the sidebar in

your theme, simply paste the code where you like:


1 <?php if ( !function_exists('dynamic_sidebar') ||
!dynamic_sidebar('MiddleSidebar') ) : ?>
2 <!–Default sidebar info goes here–>
3
4 <?php endif; ?>

Do the same for the other sidebars. Note sidebars does not have to be in yoursidebar.php file.

Additional Resource: WordPress Codex

15. Manipulate Your RSS Footer

Have you seen blogs that adds their advertisement in their RSS Feeds below each post. You can accomplish

that easily with a simple function. Paste the following codes below:
1 function wpbeginner_postrss($content) {
2 if(is_feed()){

3 $content = 'This post was written by Syed Balkhi '.$content.'Check out


WPBeginner';
4}
5 return $content;
6}
7 add_filter('the_excerpt_rss', 'wpbeginner_postrss');
8 add_filter('the_content', 'wpbeginner_postrss');
We are calling a function wpbeginner_postrss to add in each post a content before the post saying This Post

was written by Syed Balkhi and after the content Check out WPBeginner. But we add the function if(is_feed),

so it will only be displayed in RSS Feeds.

You can do this with a plugin called RSS Footer by Joost De Valk.

16. Add Post Thumbnails to Your RSS Feeds

The post thumbnail feature is usually only displayed within your site design, but you can extend that

functionality to your RSS feed with a simple function. Paste the codes below:
01 function rss_post_thumbnail($content) {
02 global $post;
03 if(has_post_thumbnail($post->ID)) {
04 $content = '<p>' . get_the_post_thumbnail($post->ID) .
05 '</p>' . get_the_content();
06 }
07 return $content;
08 }
09 add_filter('the_excerpt_rss', 'rss_post_thumbnail');
10 add_filter('the_content_feed', 'rss_post_thumbnail');

Feel free to style this however you like.

Source: Dave Redfern

17. Enable Threaded Comments in WordPress

Threaded comments is one of the best feature WordPress has. You can enable the threaded comments by

visiting your wp-admin settings > discussion area, but you still need to add the JavaScript to your header file to

make commenting easier. When developing themes, you want it to be as clean as possible, so stop cluttering

your header.php file. Simply add the following function:


1 // enable threaded comments
2 function enable_threaded_comments(){
3 if (!is_admin()) {

4 if (is_singular() AND comments_open() AND (get_option('thread_comments') ==


1))
5 wp_enqueue_script('comment-reply');
6}
7}
8 add_action('get_header', 'enable_threaded_comments');

Source: Digging into WordPress

18. Remove Error Message on the Login Page

When you enter a wrong password or an invalid username, you get an error message in the login page. So if a

hacker gets one thing right, the error message will help them identify that. You can stop helping the hacker by

adding the following function:


1 add_filter('login_errors',create_function('$a', "return null;"));

Now when there is an error, you will see an empty box:

Not recommended for sites with multiple authors.

19. Disable Search in WordPress

When using WordPress as a CMS, sometimes the search feature becomes unnecessary. You can remove the

search bar from the design, but the functionality still remains. You can add the following function and disable

the search function:


01 function fb_filter_query( $query, $error = true ) {
02
03 if ( is_search() ) {
04 $query->is_search = false;
05 $query->query_vars[s] = false;
06 $query->query[s] = false;
07
08 // to error
09 if ( $error == true )
10 $query->is_404 = true;
11 }
12 }
13
14 add_action( 'parse_query', 'fb_filter_query' );
15 add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Source: WPEngineer

20. Enable Adsense Shortcode

Adsense is one of the most popular ad elements used by bloggers. Theme designers can place the adsense box

in one spot which limits the users. If you want to give your client the ability to add the adsense anywhere, then

you can create a shortcode for the adsense using this function:
01 function showads() {
02 return '<div id="adsense"><script type="text/javascript"><!–
03 google_ad_client = "pub-XXXXXXXXXXXXXX";
04 google_ad_slot = "4668915978";
05 google_ad_width = 468;
06 google_ad_height = 60;
07 //–>
08 </script>
09
10 <script type="text/javascript"
11 src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
12 </script></div>';
13 }
14
15 add_shortcode('adsense', 'showads');

Source: Jean-Baptiste Jung’s article on Smashing Magazine

21. Change Your WordPress Feed Links without .htaccess

If you setup feedburner for your blog, then you should redirect your WordPress feeds to the feedburner feed

links. This way you will not lose any subscriber. Normally users do it with a plugin, but you can do it for your

client with this function:


01 function custom_feed_link($output, $feed) {
02
03 $feed_url = 'http://feeds.feedburner.com/wpbeginner';
04
0 $feed_array = array('rss' => $feed_url, 'rss2' => $feed_url,'atom' => $feed_u
5 rl, 'rdf' => $feed_url, 'comments_rss2' =>'');
0
$feed_array[$feed] = $feed_url;
6
07 $output = $feed_array[$feed];
08
09 return $output;
10 }
11
12 function other_feed_links($link) {
13
14 $link = 'http://feeds.feedburner.com/wpbeginner';
15 return $link;
16
17 }
18 //Add our functions to the specific filters
19 add_filter('feed_link','custom_feed_link', 1, 2);
20 add_filter('category_feed_link', 'other_feed_links');
21 add_filter('author_feed_link', 'other_feed_links');
22 add_filter('tag_feed_link','other_feed_links');
23 add_filter('search_feed_link','other_feed_links');

Source: Justin Tadlock

22. Enable a Paypal Donate Shortcode

There are times when you are writing a post, and you get an opportunity to plugin your donate link. This

function makes it easy for you by enabling a shortcode which you can use in your posts at any given time.

Paste the code below:


01 function donate_shortcode( $atts ) {
02 extract(shortcode_atts(array(
03 'text' => 'Make a donation',
04 'account' => 'REPLACE ME',
05 'for' => '',
06 ), $atts));
07
08 global $post;
09
10 if (!$for) $for = str_replace(" "," ",$post->post_title);
11
return '<a class="donateLink" href="https://www.paypal.com/cgi-
12 bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation for
'.$for.'">'.$text.'</a>';
13
14 }
15 add_shortcode('donate', 'donate_shortcode');

Make sure to change your account information and the text if you like.

Source: ThemeForest

23. Control When Your Posts are Available via RSS

All bloggers make errors that we catch after we publish the post. Sometimes even within the next minute or

two. That is why it is best that we delay our posts to be published on the RSS by 5-10 minutes. You can do that

by adding this function:


01 function publish_later_on_feed($where) {
02 global $wpdb;
03
04 if ( is_feed() ) {
05 // timestamp in WP-format
06 $now = gmdate(‘Y-m-d H:i:s’);
07
08 // value for wait; + device
09 $wait = ‘10′; // integer
10
// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-
11
functions.html#function_timestampdiff
12 $device = ‘MINUTE’; //MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
13
14 // add SQL-sytax to default $where
$where .= ” AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, ‘$now’)
15
> $wait “;
16 }
17 return $where;
18 }
19
20 add_filter(‘posts_where’, ‘publish_later_on_feed’);

This code is adding a 10 minute delay on your post being shown on the RSS Feeds, you can change it by

changing the number 10 to as many minutes as you like.

24. Customize Excerpt More […]

There is an annoying […] added at the end of each excerpt. You can change this to anything you like with a

simple function:
01 // custom excerpt ellipses for 2.9
02 function custom_excerpt_more($more) {
03 return '…';
04 }
05 add_filter('excerpt_more', 'custom_excerpt_more');
06
07 /* custom excerpt ellipses for 2.8-
08 function custom_excerpt_more($excerpt) {
09 return str_replace('[...]', '…', $excerpt);
10 }
11 add_filter('wp_trim_excerpt', 'custom_excerpt_more');
12 */

Source: Digging into WordPress

25. Custom Excerpt Length

By default the excerpt length is capped at 55 words. Many theme designers like to have the flexibility that is

why WordPress lets you customize the excerpt length with this function:
1 function new_excerpt_length($length) {
2 return 100;
3}
4 add_filter('excerpt_length', 'new_excerpt_length');

Change 100 to the length you like.

26. Display the Most Accurate Comment Count


By default, WordPress counts trackbacks, and pings as comments. This inflates the comment count which

looks really bad especially when you are not displaying the trackbacks and pings. To fix the count add the

following function:
01 add_filter('get_comments_number', 'comment_count', 0);
02 function comment_count( $count ) {
03 if ( ! is_admin() ) {
04 global $id;

$comments_by_type =
05
&separate_comments(get_comments('status=approve&post_id=' .$id));
06 return count($comments_by_type['comment']);
07 } else {
08 return $count;
09 }
10 }

27. Disable RSS Feeds

For static WordPress sites, you do not need to have an RSS feed option. You can disable the RSS feeds with

this function if you want:


1 function fb_disable_feed() {
wp_die( __('No feed available,please visit our <a href="'.
2
get_bloginfo('url') .'">homepage</a>!') );
3}
4
5 add_action('do_feed', 'fb_disable_feed', 1);
6 add_action('do_feed_rdf', 'fb_disable_feed', 1);
7 add_action('do_feed_rss', 'fb_disable_feed', 1);
8 add_action('do_feed_rss2', 'fb_disable_feed', 1);
9 add_action('do_feed_atom', 'fb_disable_feed', 1);

Source: WPEngineer

28. Display Twitter Followers Count and More

There are widgets that display Twitter followers count, but those are limited and ugly. You can use this

function to customize the way your twitter followers count look on your blog. Simply paste the code below:
01 function rarst_twitter_user( $username, $field, $display = false ) {
02 $interval = 3600;
03 $cache = get_option('rarst_twitter_user');
0 $url = 'http://api.twitter.com/1/users/show.json?screen_name='.urlencode($u
4 sername);
05
06 if ( false == $cache )
07 $cache = array();
08
09 // if first time request add placeholder and force update
10 if ( !isset( $cache[$username][$field] ) ) {
11 $cache[$username][$field] = NULL;
12 $cache[$username]['lastcheck'] = 0;
13 }
14
15 // if outdated
16 if( $cache[$username]['lastcheck'] < (time()-$interval) ) {
17
18 // holds decoded JSON data in memory
19 static $memorycache;
20
21 if ( isset($memorycache[$username]) ) {
22 $data = $memorycache[$username];
23 }
24 else {
25 $result = wp_remote_retrieve_body(wp_remote_request($url));
26 $data = json_decode( $result );
27 if ( is_object($data) )
28 $memorycache[$username] = $data;
29 }
30
31 if ( is_object($data) ) {
32 // update all fields, known to be requested
33 foreach ($cache[$username] as $key => $value)
34 if( isset($data->$key) )
35 $cache[$username][$key] = $data->$key;
36
37 $cache[$username]['lastcheck'] = time();
38 }
39 else {
40 $cache[$username]['lastcheck'] = time()+60;
41 }
42
43 update_option( 'rarst_twitter_user', $cache );
44 }
45
46 if ( false != $display )
47 echo $cache[$username][$field];
48 return $cache[$username][$field];
49 }

Then place the following code where you want to display the count in your theme file:
1 echo rarst_twitter_user('wpbeginner', 'name').' has '.
2 rarst_twitter_user('wpbeginner', 'followers_count').' followers after '.
3 rarst_twitter_user('wpbeginner', 'statuses_count').' updates.';

The above code will display something like this:

WPBeginner has 6127 followers after 1390 updates.

Source: Rarst

This list does not do justice to the power of the functions.php file. Entire theme frameworks are built solely on

this one file. You can use it to add custom post types, create theme admin panels, and much more.

Additional Resources

Digging into WordPress – One of the best e-books for WordPress developers. It has some of the best uses of

functions.php file.

Go to Any Design / Development related blog and type functions.php in their search to see what you can do

with this file. Just on our site, you should be able to find 30+ articles about the uses of functions.php file. Try it

for yourself:http://www.wpbeginner.com/?s=functions.php

Vous aimerez peut-être aussi