9 WordPress Codes To Spice Up Your Blog and Improve UX

The beauty of PHP code. ;) Ready to make it do magic on WordPress?

By Sauce Babilonia via Compfight (CC)

WordPress is easy to configure and install, ready to go as soon as you publish your blog.

But relying on WordPress’ default options might result in a loss on your behalf:

  • Less functionality
  • Bored users (who see the same stuff on every WP sites they stumble upon)
  • Drops in search engine rankings.

You have a flexible tool in your hands, that you can tweak to turn it into something pleasant to use and efficient to rely upon. Why not spice things up for your users (and yourself)?

This article wants to help you make your WordPress-based website fun and helpful for your users by adding interesting code snippets that will also enhance your SEO.

Give them a try and let me know how they worked out for you! ;)

9 Codes To Enhance Your WordPress Blog

I will offer you two types of code snippets in this post:

  1. Codex codes
  2. Code snippets and widgets

Codex codes are PHP snippets I wrote myself (with the help of my fiance, Simone) strictly using the WordPress.org Codex as a reference.

Code snippets and widgets are ready-made pieces of PHP code (or WordPress plugins) that are freely available on other websites and on WordPress.org, but I also included snippets my fiance and I wrote from scratch using open and Codex references.

Both types of codes are easy to implement and install, but you may want to start with widgets and plugins if you’re unsure how to manipulate code.

I understand that 9 code snippets may not be enough for those of you who like to experiment with lots and lots of different code, so I’m sure our Robert Ludrosky’s 25 handy code snippets for WordPress Developers will satiate your hunger (at least for a while). ;)

Codex Codes

1. Differentiate Sticky Posts

To make WordPress check if your current post is a sticky post – and display it accordingly – you can use the Codex boolean function:

<?php is_sticky(); ?>

The function alone will only return TRUE or FALSE values, so what you can do here if write a conditional construct (if/else) to manage your sticky posts. An example:

<?php if is_sticky() {
  the_title();
  the_time('M, d, Y');
  the_excerpt();
}
else {
  include 'post-template.php';
}

In this sample usage, I displayed the sticky post as a box containing only the title, the post date and the excerpt (not the entire post), while the standard template for the other posts is contained in post-template.php.

Each type of post will have its own CSS stylesheet, but we’re not defining styles here; only templates.

Single.php is your default template for single posts (you’ll find it included with every default WP theme).

If you have developed your own WP theme but you have setup no templates for single posts, you can follow the Codex guide here.

2. Displaying Post URL

This one might be fun to add to your template. If you want your readers to get the URI for each of your pages (or posts), just use the following tag within your single.php, page.php or even index.php template:

<a href="<?php echo get_page_link();?>"><?php echo get_page_link(); ?></a>

Instead of using the_permalink, that’s the most obvious choice and works for all cases, WP allows you to use two alternative forms for posts and pages:

<?php echo get_post_permalink(); ?>
 <?php echo get_page_link(); ?> 

For example, your page template can include:

<p>Link: <a href="<?php echo get_page_link();?>"><?php echo get_page_link(); ?></a></p>

3. Retrieve and Display Post ID Number

Even when you setup your permalink structure to be user- and SEO-friendly, you can still show your visitors the post ID by adding this simple function to your meta line:

<?php the_ID(); ?>

Sample usage:

<p class="meta">Posted by Author's Name. Post ID is <?php the_ID(); ?></p>

4. List Categories By ID

The WordPress standard function is:

<?php get_all_category_ids() ?>

Here is an example I used on one of my blogs, written using code from the Codex and a topic on StackOverflow:

<?php
 $category_ids = get_all_category_ids();
 foreach($category_ids as $cat_id) {
   $cat_name = get_cat_name($cat_id);
 $category_link = get_category_link($cat_id); //we need the cat link for the URL to work!
 echo "<a href=\"{$category_link}\">{$cat_id}</a>: {$cat_name}<br/>";
 }
 ?>

… and how it’s displayed:

category WP code

Note: get_all_category_ids() is now a deprecated function, but you can still use it without problems, like I do on my blog (screenshot above). However, if you wish to use the new function for this snippet, visit the get_terms() page of the Codex.

What does this code do?

The code gets all category IDs and the category name for each ID, then it links the ID to the category link, while it displays the category name after the “:” — hence the echo() expression <a href=\"{$category_link}\">{$cat_id}</a>: {$cat_name}<br/>.

5. A Detailed Users/Authors Page For Your Blog

Have you ever wanted to build a custom page that would display all your blog authors or users without having to rely on a plugin?

Well, you can create your own custom Authors/Users page with only a text editor, an FTP uploader and your beloved WordPress Dashboard.

First of all, you need to create a copy of your page.php file. Rename your copy into any name — I named mine users.php.

Add the template tag to the top of this template for WordPress to recognize it as a template, then go to your Dashboard -> Pages -> Add New and create a page for your list of Users/Authors. Return to the Pages list, click Quick Edit under your new page title and select your new template from the Template drop-down menu. Save your changes.

Now open your users.php (or whatever you named it) file and apply the following code:

 <?php
 $result = count_users();
 echo 'There are ', $result['total_users'], ' total users';
 foreach($result['avail_roles'] as $role => $count)
 echo ', ', $count, ' are ', $role, 's';
 echo '.';
 ?> 

This code uses the count_users function is listed as “default usage” in the Codex. You can view a live example of this code at http://robocity.in/users/.

After that code, let’s add something about the blog admin:

<?php printf( __( 'Number of posts published by user "Leaders": %d', 'text-dom-here' ), count_user_posts(1) ); ?>

I used the count_user_posts function here, following the usage format suggested by the Codex.

The function get_userdata is good to show the correlation between a certain username and the real name of the person using it. See below:

<?php $user_info = get_userdata(1);
      $username = $user_info->user_login;
      $first_name = $user_info->first_name;
      $last_name = $user_info->last_name;
      echo "$first_name $last_name logs into their WordPress site with the username of $username.";
?>

Now, this is the most interesting function you can use on your Authors/Users page — the get_users function:

<?php
$blogusers = get_users( 'blog_id=1&orderby=nicename&role=administrator' );
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
    echo '<span>' . esc_html($user->user_login) . '&nbsp;-&nbsp;' . esc_html($user->user_email) . '</span><br/>';
}
?>

This function will retrieve a list of users according to certain parameters that you can configure in the code. In the example above (taken from the Codex page and edited to fit my Users page at Robocity.in), I want to get a list of administrators for blog ID 1 (current blog) ordered by ‘nicename’, and for each user, I want to display username and email in a sentence of the type “Username – name@example.com”.

If you like to show logged in users something about themselves, you may use the get_currentuserinfo function to retrieve, say, the user’s name and address. I didn’t use this function in my example, but creativity doesn’t know limits, right? ;)

Code Snippets & Widgets

6. Alternative… Archives!

nicer blog archivesImagine if you could replace your old sidebar Archives list — that keeps growing as your blog grows and forces users to scroll — with a snippet like the one you can see here on the right.

Wouldn’t it make things easier for your readers to catch your blog age and depth of archives at a glance? :)

My fiancé and I wrote this simple snippet using the get_post from the Codex and a simple dropdown menu for the list of archives. We created our own functions to make the idea work out well.

<?php
 function formatPostDate($postId, $format = '%F') {
 $post = get_post($postId);
 $output = strftime($format, strtotime($post->post_date));
 return $output;
 }

function getLastPostID() {
 list($post) = get_posts(array('posts_per_page' => 1));
 return $post->ID;
 }
 ?>

<p>This blog has posts since <?php echo formatPostDate(1, '%B %e, %Y'); ?>.<br/>
 Last post was published on <?php echo formatPostDate(getLastPostID(), '%B %e, %Y'); ?>.</p>

<p>Do you wish to visit a specific archive?</p>

<select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
 <option value=""><?php echo esc_attr( __( 'Select Archive' ) ); ?></option>
 <?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option', 'show_post_count' => 1 ) ); ?>
 </select>

What does this code do?

The function formatPostDate takes the post’s ID and date format and returns a date in a format of your choice. The second function, getLastPostID, takes an array of posts containing only one post and returns its ID.

To get the first post of the blog – generally with ID=1, we write echo formatPostDate(1, ‘%B %e, %Y’) in the first paragraph: this code uses the formatPostDate function and takes as parameters the post ID #1 and a standard English format for the date, and returns the date.

To get the last post of the blog, we use formatPostDate(getLastPostID(), ‘%B %e, %Y’) to get the ID of the last post and a date format (again, in English) and print the date on screen.

7. Check if visitor uses a mobile device

Muneeb at WP-Snippets.com shared an interesting code snippet (a function) to check if a visitor on your site is using a mobile device.

The code is available here.

This function helps with mobile optimization, as it’s useful if you want to show certain function only to mobile users or to exclude mobile users from certain website features.

8. Use the if/else construct to manipulate your page sidebar content

This code snippet is based on WordPress’ Codex, but I placed it in this section because it allows for much creativity and you may be able to find ready-made snippets on the Web.

Suppose that you want to use multiple sidebars on your site. You may fill your sidebar with divs and sections, but the more that file grows (even if you use widgets) the heavier it gets.

The Codex comes to you rescue with the get_sidebar($name) function. The usage is simple:

  1. Create (say) a sidebar for your Quotes snippets. Name it sidebar-quotes.php
  2. In the main sidebar.php file (or the header or index file, according to your WP theme structure) write get_sidebar(“quotes”); to include the “sidebar-quotes.php” file.

You will get a slimmer sidebar with calls to other sub-sidebars, that you can optimize with if/else constructs if you know a bit of PHP coding for WordPress.

You may not know this, but when you use the generic get_sidebar() code, that will include “sidebar.php” because you didn’t add a $name argument. This is the default usage. When you add a “-name” after “sidebar*.php”, you can call that name addon with the $name arg.

If you have ads, special offers or sidebar functions that you want to display on certain pages of your blog or code that will overload your standard sidebar, you will find this code snippet a life saver for UX.

9. A tool for integrating code snippets into your WordPress site

codesnippets screenshot

Code Snippets is a free WordPress plugin created by Shea Bange that allows you to easily add code snippets to your blog.

The nice thing about this plugin is that you no longer have to edit your functions.php file, but you can add custom code directly from your WordPress Dashboard. Basically, you can add code snippets like you would add a new post or page.

Tom Ewer at WPMUDev.org wrote an interesting introduction to this plugin, but the most useful resource I found so far for Code Snippets is the plugin support forum at WordPress.org.

Over to you!

Share your WordPress coding experiments in the comments below! And feel free to ask questions about the snippets introduced in this post.