10 Tips To Optimize Your WordPress Theme

Advertisement

The beauty of WordPress is in how easy it is to adapt for different tasks. One can extend it with just a couple of lines of code. In this post, we’ll review 10 shortcode snippets that will tweak and optimize your WordPress theme. You can add all of these code snippets to the functions.php file in your WordPress theme.

1

Limit The Excerpt’s Word Count

One thing that can go wrong in WordPress magazine themes is when users include too many words before the more tag. Sure, they could handcraft the excerpt in the dedicated field, but on a website that has hundreds of posts and on which the text above the more tag has always been used as the excerpt, going back to create excerpts for all of those posts by hand would be cumbersome. In this case, we can limit the number of words shown in the excerpt by using this code:

add_filter('excerpt_length', 'ilc_excerpt_length');
function ilc_excerpt_length( $length ){
  return 10;
}

Here, we’re using a WordPress filter hook, which is a function that parses and (usually) modifies data before it gets stored in the database or displayed on a page. In this case, we’re setting the number of words shown in the excerpt to 10.

Add A Favicon Using A WordPress Hook

Hooks allow us to insert custom code without touching the template. This gives us a lot of flexibility, because now, whenever we need to change something, we only have to change the function that’s plugged into a certain hook. For example, you can add a favicon to your website without touching the header.php file, just by plugging a function into the wp_head hook:

add_action( 'wp_head', 'ilc_favicon');
function ilc_favicon(){
  echo "<link rel='shortcut icon' href='" . get_stylesheet_directory_uri() . "/favicon.ico' />" . "n";
}

The favicon.ico file should be located at the root of your theme. We’re now using an action hook, which is a function that is triggered at specific points during an execution by WordPress’ core. In this case, the hook triggers any function that’s attached to it when a page is launched in the browser. But other hooks can be triggered when saving a post, registering a user and so on. Some themes even have their own action hooks, which, like WordPress’ core action hooks, can be used to launch functions at specific points of an execution.

Detect Safari On iOS

Nowadays, websites serve mobile versions using different techniques. WordPress offers a safe way to check for the mobile Safari browser so that you know when a visitor is using an iPhone or iPad.

WordPress sets the $is_phone variable internally, and you can use it to embed an alternative style sheet, show alternative content or display a different video format. In the following example, the $is_iphone variable is run, and different style sheets are applied depending on the value returned:

add_action('wp_print_styles', 'ilc_enqueue_styles');
function ilc_enqueue_styles(){
  global $is_iphone;
  if( $is_iphone ){
    wp_enqueue_style('iphone-css', get_stylesheet_directory_uri() . '/iphone.css' );
  }
  else{
    wp_enqueue_style('common-css', get_stylesheet_directory_uri() . '/common.css' );
  }
}

In this case, we’re using the standard WordPress function wp_enqueue_style2 to add styles to the head element of the Web page. The action that we’re attaching our function to is wp_print_styles; so, we’re basically telling WordPress to output the relevant style sheet when it prints all of the other required style sheets.

Remove Elements From The Header

WordPress outputs several things in the head section. In particular, the generator meta tag, the RSD link and the wlwmanifest link won’t be of much use to many users:

<meta name="generator" content="WordPress 3.2.1">
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://example.com/xmlrpc.php?rsd">
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://example.com/wp-includes/wlwmanifest.xml">

Some bloggers say you should get rid of the generator meta tag so that no one can tell which version of WordPress you’re using. But remember, you should always be using the latest version anyway.

If you don’t need XML-RPC functionality, you can remove the RSD link (the second line in the snippet above). The same goes for if you don’t use Windows Live Writer: you can safely remove the third element.

In this case, you can add this code:

add_filter('the_generator', create_function('', 'return "";'));
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');

These lines will remove the corresponding elements in the snippet above.

Redirect WordPress Feeds To FeedBurner

It’s great that WordPress offers feeds out of the box. But if you want statistics about your subscribers, you’ll have to use FeedBurner or a similar service. To redirect your feed to one of these, use the following snippet. Thus, if you try to go to http://www.smashingmagazine.com/feed3, you’ll be redirected to FeedBurner’s feeds for Smashing Magazine4.

add_action('template_redirect', 'ilc_rss_redirect');
function ilc_rss_redirect() {
  if ( is_feed() && !preg_match('/feedburner|feedvalidator/i', $_SERVER['HTTP_USER_AGENT'])){
    header('Location: http://feeds.feedburner.com/smashingmagazine');
    header('HTTP/1.1 302 Temporary Redirect');
  }
}

Replace http://feeds.feedburner.com/smashingmagazine with the URL for your own feed from FeedBurner.

Show Featured Images In Feed

To encourage subscribers to visit your website, rather than letting them just consume content through your RSS feed, you might want to display only the excerpt and featured image of posts. But WordPress doesn’t display the featured image in the RSS feed by default. Use the following code to do so. You can even add HTML to it.

add_filter('the_content_feed', 'rss_post_thumbnail');
function rss_post_thumbnail($content) {
  global $post;
  if( has_post_thumbnail($post->ID) )
    $content = '<p>' . get_the_post_thumbnail($post->ID, 'thumbnail') . '</p>' . $content;
  return $content;
}

Show Content Only To RSS Subscribers

To increase subscribers to your RSS feed, you could offer a gift available only to them. The code below creates a new shortcode65 with which to wrap content in order to hide it from regular visitors but not from RSS subscribers.

add_shortcode( 'feedonly', 'ilc_feedonly' );
function ilc_feedonly( $atts, $content = null ) {
  if( is_feed() ) return '<p>' . $content . '</p>';
  else return;
}

Show Content Only To Logged-In Users

In the same vein, you could show content only to registered users of your website. The code below creates a new shortcode65 with which to wrap content in order to hide it from casual visitors but not logged-in users.

add_shortcode( 'loggedin', 'ilc_loggedin' );
function ilc_loggedin( $atts, $content = null ) {
  if( is_user_logged_in() ) return '<p>' . $content . '</p>';
  else return;
}

Display Links For Sharing Posts On Social Networks

If, for some reason, you don’t want to use the standard Facebook, Twitter and other social-networking buttons for sharing posts, you can add your own links with the code below, perhaps using it in conjunction with one of Smashing Magazine’s icon sets, such as Flavours7.

Here, we’ll be filtering the content using the the_content function. But, unlike what we did when we adjusted the excerpt’s length or removed the generator meta tag, we don’t want to overwrite it, but rather to append our links to it. So, this filter returns the post’s original content, concatenating our social-networking links right after it.

add_filter( 'the_content', 'ilc_share' );
function ilc_share( $content ) {
  global $post;
  $postlink  = get_permalink($post->ID);
  $posttitle = get_the_title($post->ID);
  $html = '<ul class="share-entry">';
  // Twitter
  $html .= '<li><a class="share-twitter" title="Share on Twitter" rel="external" href="http://twitter.com/share?text='.$posttitle.'&url='.$postlink.'">Share on Twitter</a></li>';
  // Facebook
  $html .= '<li><a class="share-facebook" title="Share on Facebook" rel="external" href="http://www.facebook.com/share.php?u=' . $postlink . '">Share on Facebook</a></li>';
  // LinkedIn
  $html .= '<li><a class="share-linkedin" title="Share on LinkedIn" rel="external" href="http://www.linkedin.com/shareArticle?mini=true&url=' . $postlink . '&title=' . $posttitle . '">Share on LinkedIn</a></li>';
  // Digg
  $html .= '<li><a class="share-digg" title="Share on Digg" rel="external" href="http://digg.com/submit?url=' . $postlink . '">Share on Digg</a></li>';
  // StumbleUpon
  $html .= '<li><a class="share-stumbleupon" title="Share on StumbleUpon" rel="external" href="http://www.stumbleupon.com/submit?url=' . $postlink . '&title=' . $posttitle . '">Share on StumbleUpon</a></li>';
  // Google+
  $html .= '<li><a class="share-googleplus" title="Share on Google+" rel="external" href="https://plusone.google.com/_/+1/confirm?url=' . $postlink . '">Share on Google+</a></li>';
  $html .= '</ul>';
  return $content . $html;
}

This code will add the links both in the full view for posts and on the archive pages (such as the category and tag pages). If you want them to appear only in the full view for posts, then add the following right before global $post;:

if( !is_singular() ) return $content;

This way, the links will be appended only when the user visits the full post or the page for an image.

Add Logo To The Log-In Page

To add your logo to the log-in page for administrators, use the login_head action hook, which executes all functions that are attached to it in the log-in page’s head element. We’re doing two things here: changing the logo, and changing the link that it points to.

add_action( 'login_head', 'ilc_custom_login');
function ilc_custom_login() {
  echo '<style type="text/css">
  h1 a { background-image:url('. get_stylesheet_directory_uri() . '/images/login-logo.png' . ') !important; margin-bottom: 10px; }
  padding: 20px;}
  </style>
  <script type="text/javascript">window.onload = function(){document.getElementById("login").getElementsByTagName("a")[0].href = "'. home_url() . '";document.getElementById("login").getElementsByTagName("a")[0].title = "Go to site";}</script>';
}

The CSS code will replace the WordPress logo with your own. You can adjust the path to the image in the fourth line of the code above to suit your theme.

In addition, the JavaScript changes the logo’s URL, so that you jump not to wordpress.org but to your own home page.

Closing Thoughts

We’ve seen how to customize WordPress’ social-network links and icons, how to show content only to logged-in users, how to customize the RSS feed and more. But the most important thing to take away is that you can build on this in endless ways. For example, you could add social-network links only in your feed, or add your logo to the bottom of the feed, or customize the log-in page using CSS, to name just a few possibilities.

Action hooks and filters are effective tools for tweaking the output of a theme, whether written to the database or run in the visitor’s browser. You can read more about actions8 and filters9 in the WordPress Codex.

(al)

Footnotes

  1. 1 http://www.smashingmagazine.com/2011/12/07/10-tips-optimize-wordpress-theme/
  2. 2 http://codex.wordpress.org/Function_Reference/wp_enqueue_style
  3. 3 http://www.smashingmagazine.com/feed
  4. 4 http://feeds.feedburner.com/smashingmagazine
  5. 5 http://codex.wordpress.org/Shortcode_API
  6. 6 http://codex.wordpress.org/Shortcode_API
  7. 7 http://www.smashingmagazine.com/2009/01/23/friday-freebies-flavours-icon-set-and-cute-tweeters-icon-set/
  8. 8 http://codex.wordpress.org/Plugin_API/Action_Reference
  9. 9 http://codex.wordpress.org/Plugin_API/Filter_Reference

↑ Back to topShare on Twitter

Advertising
  1. 1

    Good article, but using JS to change the logo url on the login page is unnecessary, you can just filter login_headerurl like so:

    function put_my_url(){return ( home_url() );}
    add_filter('login_headerurl', 'put_my_url');

    3
  2. 2

    Any reason why you are using a 302 Temporary Redirect to feedburner and not a 3.1 Moved Permanently? 302 are better for SEO.

    2
    • 3

      This is because if later you decide to stop redirection to Feedburner, your readers will still be able to use the original RSS URL from your blog! So 302 in this case is much better option! (And plus, what are SEO and RSS feeds having in common? I guess, nothing…)

      2
  3. 5

    Hi,

    Can’t you delete header elements directly from your theme’s files?

    -2
  4. 6

    Jonathan, that’s cool, thanks for sharing.

    Rob, good point. I assume you meant “301 are better for SEO” and it’s a debatable subject. Actually, Feedburner doesn’t creates or generates the RSS feed, your site does. The feed created by Feedburner depends on your feed. You can decide to change your RSS feed service at any time, hence the reasoning behind a 302.

    Note that this hack is meant for feeds located under feedburner.google domain so things might be different using MyBrand service which is something I’m not familiar with.
    One of the main issues with 302 is that not all search engines handle it in the same way, probably because it’s prone to hijacking, but if your redirection is legit, which is the case here, you’re safe.

    George, the elements removed in the code snippet are generated on the fly by WordPress. They are not in your header.php file.

    1
  5. 7

    Adeniyi Moses Adetola

    December 9, 2011 9:27 am

    Very interesting article and nice tricks I would try out couple in my next word press project. Thanks.

    1
  6. 8

    How would three confusing lines in the functions file be faster than one simple line in the header file to add a favicon?

    -1
    • 9

      You’re welcome Adeniyi, hope it’s useful for you.

      Alan, this is useful if you’re building a child theme and for some reason you can’t modify header.php or want to keep the changes to the templates to a minimum.
      Another example is if you have a framework that you want to reuse and want to avoid cluttering your header.

      0
  7. 10

    Clifford Blodgett

    December 13, 2011 7:15 am

    Great piece, lots of great snippets there that I have saved for later!

    1
  8. 11

    Hi,
    I’m trying to add my customized logo in the log-in page, but I can’t. When I change the functions.php file, it says lots of warnings like this: “Warning: Cannot modify header information – headers already sent by (output started at /home/content/51/7958051/html/wp-content/themes/rockwell_v1.7.1/functions.php:931) in /home/content/51/7958051/html/wp-login.php on line 353″
    Please, what I’m doing wrong?
    The code I’m adding:

    <?php
    add_action( 'login_head', 'ilc_custom_login');
    function ilc_custom_login() {
    echo '
    h1 a { background-image:url(‘. get_stylesheet_directory_uri() . ‘/images/my-logo-login.png’ . ‘) !important; margin-bottom: 10px; }
    padding: 20px;}

    window.onload = function(){document.getElementById(“login”).getElementsByTagName(“a”)[0].href = “‘. home_url() . ‘”;document.getElementById(“login”).getElementsByTagName(“a”)[0].title = “Go to site”;}’;
    }
    ?>

    0
    • 12

      Miguel,

      This is not something that you add in wp-login.php. You want to add this to your ‘functions.php’ file.

      0
  9. 13

    How can wordpress know if one is a feedburner subscriber to show or not to show content?

    0
  10. 14

    Sam Daniel Mathew

    June 30, 2012 4:54 am

    Hello admin,
    This is a wonderful article and I like it very much.I have a request,can I add this article in my blog in your banner.My website is http://www.chrisamdesigns.com I really hope that you will shoot me a mail.
    Cheers..

    1

↑ Back to top