WordPress Cheatsheet: 15 Things You Can Do with functions.php
Note: This article assumes you have a working knowledge of PHP and WordPress Theme structure.
functions.php
is a little genie that lives in your WordPress theme subdirectory. Basically, it’s your theme’s powerhouse. You can add tons of functionality to your theme without bothering with plugins.
Here are 15 fantastic things you can do with functions.php
:
1. Painlessly Integrate Google Analytics
Once you sign up for Google Analytics, you receive a tracking code with your unique tracking ID that needs to be added to your website. Unfortunately, it needs to be added to every page you want to track.
Go to Google Analytics >> Admin. Under Property, select the website you want to track, and on Tracking Code (under Tracking Info).
Now go to WordPress, open functions.php
and add the following code:
<?php
add_action('wp_footer', 'add_ga_script');
function add_ga_script()
{
?>
// Add your Google Analytics Tracking Code here
<?php
}
?>
Source: Adding Google Analytics Code
This creates a function add_ga_script
and sets it to run on all pages that have the wp_footer
string.
2. Make AdSense Flexible
AdSense helps bloggers make money, but those click-rates aren’t forthcoming with highly relevant ads placed in a corner through sidebar.php
, as themes are wont to do. That translates to lower earnings.
You can create a shortcode that places the ads within the post. Here’s how:
function showads() {
return '<div id="adsense"><script type="text/javascript"><!--
google_ad_client = "pub-XXXXXXXXXXXXXXXX";
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>
';
}
add_shortcode('adsense', 'showads');
(Source)
This creates a 468×60 ad that you can place anywhere in the post by writing [adsense]
inside HTML container tags. You can style it through the style.css
file too.
3. Make Post Excerpts As Long As You Want
You can change the length of your post excerpts to as many words as you like (instead of sticking to default 55) by adding this to functions.php. (Remember to change the return value to your specification)
function new_excerpt_length($length) {
return 75;
}
add_filter('excerpt_length', 'new_excerpt_length');
4. Remove Trackbacks and Pingbacks from Comment Count
WordPress counts trackbacks and pings as comments instead of spam. You may have selective comments displayed, but trackbacks and pings will increase your comment counts. That simply feels like you are looking at your visitors and commenters as fools.
Here’s how to fix this:
add_filter('get_comment_number', 'comment_count', 0);
function comment_count( $count ) {
if ( ! is_admin() ) {
global $id;
$comments_by_type = &separate_comments(get_comments('status=approve&post_id=' . $id));
return count($comments_by_type['comment']);
} else {
return $count;
}
}
(Source)
This filter leaves out trackbacks and pingbacks (and other comments that remain unapproved) from the comment count.
5. Display ‘Under Maintenance’ Page
Here’s a little snippet you can add to manually display a ‘Maintenance’ page to visitors
function maintenance_mode() {
if ( !current_user_can( 'edit_themes' ) ) {
wp_die('<h1>Sorry! We are running maintenance and will be back online shortly</h1>’);
}
}
add_action('get_header', 'maintenance_mode');
6. Keep your site Copyright Up To Date
If you are regularly adding original, unique content, you should also remind your visitors that the content is owned by you. Here is a neat code snippet to keep the © (copyright) date updated dynamically with post date stamps:
function my_copyright() {
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;}
Add the last line of code where you want to display the dynamically generated copyright (like ©2011-2016)
7. Customize your Footer
Add affiliate and other important links to your footer with this code snippet:
function remove_footer_admin () {
echo 'Powered by <a href="http://www.wordpress.org" target="_blank">WordPress</a> | Created by <a href="http://www.yoursiteurl.net" target="_blank">Your Site Name</a>';
}
add_filter('admin_footer_text', 'remove_footer_admin');
(Source)
Add <?php echo my_copyright(); ?>
where you want to display the dynamically generated copyright (like ©2011-2016)
8. Remove Error Message from Login
This adds another roadblock in a hacker’s way who is trying to access your WordPress. Login error message shows you which field (username or password) needs to be edited for access, and if a hacker gets even one of the two right, their work is cut down by half.
If your security plugin doesn’t do it, add this simple line to keep hackers guessing:
add_filter('login_errors',create_function('$a', "return null;"));
9. Remove WordPress Version Details from Public Eyes
If you are running on anything but the latest version of WordPress, then your version details can spell a lot of trouble. Previous versions (and their security flaws) are out in the light, and lazier hackers use that information to take over sites that were happy with the old version.
If your security plugin doesn’t do it, here’s how you can remove version details from the RSS and header:
function site_remove_version() {
return '';
}
add_filter('the_generator', 'site_remove_version');
10. Spice-up RSS Feeds with Post Thumbnails
This snippet makes your RSS feeds look livelier by automatically displaying post thumbnails (if a post has them).
function rss_post_thumbnail($content) {
global $post;
if(has_post_thumbnail($post->ID)) {
$content = '<p>' . get_the_post_thumbnail($post->ID) .
'</p>' . get_the_content();}
return $content;}
add_filter('the_excerpt_rss', 'rss_post_thumbnail');
add_filter('the_content_feed', 'rss_post_thumbnail');
(Source)
11. Nested Comments
WordPress has a great comments section, and you can improve how active site users and visitors interact by enabling comment threading. Add this to functions.php
:
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');
(Source)
12. Automatically Add a PayPal ‘Donate’ Hyperlink in a Post
Donations are real, tangible proofs of love and appreciation. Here’s how you can add a PayPal donation link via an easy to use shortcode:
function donations_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', 'donations_shortcode');
(Source)
The function will be called when you write [donate]
in your posts.
13. Add a Custom Dashboard Logo
Remind your clients/customers or maybe your own site management team of your brand by adding a custom logo to replace WordPress’ “w”.
add_action('admin_head', 'my_custom_logo');
function my_custom_logo() {
echo '
<style type="text/css">
#header-logo { background-image: url('.get_bloginfo('template_directory').'/images/custom-logo.gif) !important; }
</style>
';
}
(Source)
14. Change Gravatar
Another sweet branding opportunity: Upload a custom Gravatar image to your theme’s image folder. After that, add this to functions.php
:
add_filter( 'avatar_defaults', 'custom_gravatar' );
function custom_gravatar ( $avatar ) {
$custom_avatar = get_stylesheet_directory_uri() . '/images/gravatar.png';
$avatar[$custom_avatar] = "Custom Gravatar";
return $avatar;
}
(Source)
15. Add Author Profile Fields
Give aspiring authors and bloggers another reason to write for you by adding custom fields on author profile pages. Here’s how to add Twitter and Facebook fields:
function author_social_fields( $contactmethods ) {
$contactmethods['twitter'] = 'Twitter';
$contactmethods['facebook'] = 'Facebook';
return $contactmethods;
}
add_filter('user_contactmethods','author_social_fields',10,1);
About the Author
Lucy Barret is a blogger by hobby and loves to share everything related to web development. She is an expert of converting PSD to WordPress theme at HireWPGeeks Ltd. and has an experienced team of developers to assist her. Follow her on social media channels like Facebook and Twitter.