WordPress Plugin: Latest Posts by Author

latest-by-author

Update: The plugin has gone through a number of revisions since I first published this post. See: http://wordpress.org/extend/plugins/latest-posts-by-author/ for the latest versions. The code posted below is from version 0.6.

I just posted my first plugin to wordpress.org. It creates an unordered list of the most recent posts by a given author. It can be called both from within a post using a shortcode or from within a theme file. Check out Latest Posts by Author at wordpress.org for more details.

To demonstrate just how easy it is to create a plugin for WordPress, I’m posting the plugin code below.

<?php

/*
Plugin Name: Latest Posts by Author
Plugin URI: http://wordpress.org/#
Description: Displays a list of recent posts by the specified author
Author: Alex Mansfield
Version: 0.6
Author URI: http://alexmansfield.com/
*/

function latest_posts_by_author($array) {
 extract(shortcode_atts(array('author' => 'admin', 'show' => 5, 'excerpt' => 'false'), $array));

 global $wpdb;
 $table = $wpdb->prefix . 'users';
 $result = $wpdb->get_results('SELECT ID FROM '.$table.' WHERE user_login = "'.$author.'"');
 $id = $result[0]->ID;
 $table = $wpdb->prefix . 'posts';
 $result = $wpdb->get_results('SELECT * FROM '.$table.' WHERE post_author = '.$id.' AND post_status = "publish" AND post_type = "post" ORDER BY post_date DESC');
 $i = 0;
 $html = '<ul>';
 foreach ($result as $numpost) {
 $html .= '<li><a href="'.get_permalink($numpost->ID).'">'.$numpost->post_title.'</a>';
 if($excerpt == 'true'){
 $html .= '<p>'.$numpost->post_excerpt.'</p>';
 }
 $html .= '</li>';
 $i++;
 if($i == $show){
 break;
 }
 }
 $html .= '</ul>';

 return $html;
}

add_shortcode('latestbyauthor', 'latest_posts_by_author');

?>
  • PublishedAugust 11, 2009
  • UpdatedFebruary 16, 2012
  • Posted InPlugins, Wordpress
  • DifficultyAdvanced
  • Tested With2.8 - 3.3

Adding Custom WordPress Shortcodes

shortcode

Introduced in WordPress 2.5, shortcodes make it easy to include pieces of code or content in multiple places across your site without having to repeatedly copy and paste. Also, if you need to go back and make adjustments, with shortcodes you don’t need to make the adjustment on every page, you just edit the shortcode source.

For example, just the other day I was creating an order form that had to appear on a number of different pages across the site I was working on. Each form was exactly the same with the exception of the item number. Since shortcodes can be made to accept arguments, I could call the shortcode and pass it the item number to use in the form (for those of you haven’t done any programming, arguments have nothing to do with arguing. Parameters or variables might be a more understandable words). Here’s how easy it was to include the form in a page:

[order item="59336"]

That tells WordPress to go get the code associated with [order] and set the item number to 59336. Now lets take a look at how to actually create the functionality I’ve been describing. It’s actually pretty simple.

Open up your functions.php file and scroll to the bottom. You’ll want to add your code just above the closing PHP tag (?>). Here’s how you would add an order form similar to the one I described earlier. Keep in mind that an order form is just one of hundreds of uses for shortcodes. My purpose is to show you how to create shortcodes, not order forms, so I’m only going to explain the code that relates to the creation of the shortcode. Here’s the code:

function orderform($item_nbr) {
extract(shortcode_atts(array("item" => '0'), $item_nbr));
return <form method="post"><input name="item_number" type="hidden" value="' . $item . '" />
<label for="quantity">Quantity:</label>
<input id="quantity" name="quantity" size="8" type="text" />
</div>
<div><input id="submit" type="submit" value="Place Order" /></div>
</form>';
}

Take a look at the first line. It starts the function (function), gives it a name (orderform), and then assigns a name to the variable that holds the shortcode arguments ($item_nbr).

After that, you have to extract the actual value from the item_nbr variable to get the individual arguements. This is accomplished by line 2. The first part (array…) sets up the default values of the array while $item_nbr is the actual list of arguments being passed in by the shortcode.

Next you need to return the form as a string so that it can be displayed in the post. Notice this section of line 3:

' . $item . '

This breaks out of the HTML string and inserts the item number that you passed in with the shortcode. Note that the variable name is “$item” which you set along with the default value when you extracted the array in line 2.

That’s it for the writing the function. Now you just need to let WordPress know about it. Just after the function, still in the functions.php file, add this line:

add_shortcode('order', 'orderform');

The first argument (‘order’) is the keyword for use in the shortcode. The second argument is the name of the function (‘orderform’). So once again, all you have to do to include the form inside a post is use this short piece of code:

[order item="59336"]

Feel free to play around with the code and let me know if you have any questions.

WordPress Custom Headers

wordpress-custom-headers

This post is about adding the custom header functionality to a WordPress theme. If you were looking for existing themes that support custom headers, I suggest you try the WordPress free themes directory.

Since version 2.1, WordPress has allowed custom headers to be added to themes. I don’t really have a use for it on my own blog, but I’d like to offer that functionality in the themes I release to the public. So last night I waded though some documentation and existing code to figure out just how it’s done. It’s actually pretty simple, so even if you don’t have much experience with WordPress theming, you should be able to follow along.

1. Define the header properties

First you need to tell WordPress a few things about your header. There are four things you should specify:

  1. Header image location (the path to the image)
  2. Header width
  3. Header height
  4. Text color

These definitions go in the function.php file in your WordPress theme. Here’s what it looks like:

define('HEADER_IMAGE', '%s/images/header.jpg');
define('HEADER_IMAGE_WIDTH', 960);
define('HEADER_IMAGE_HEIGHT', 150);
define('HEADER_TEXTCOLOR', '444444');

As you can see, I use a file called header.jpg and I keep it in a folder called images within my WordPress theme. You’re free to name your image something else if you prefer, or even put it in a different folder. You’ll want to leave the “%s/” as it is though, since it points to the location of your theme directory. The next two lines specify the width and height of the header image. WordPress will allow the user to crop any picture they upload to the dimensions you specify to make sure their images fit perfectly into your design. The last line is for setting the color of the header text. The user will have the option of changing colors or hiding text all together, so just set the color to whatever works best with your default background and rest assured that if they change the background, they can change the text to match.

2. Add some style

Now you need to create a function that will provide the styles associated with header image in your theme. All you’re really doing is wrapping some CSS in a PHP function like this:

function header_style() {
?>
<style type="text/css">
#header{
background: url(<?php header_image(); ?>)  no-repeat;
height: <?php echo HEADER_IMAGE_HEIGHT; ?>px;
width: <?php echo HEADER_IMAGE_WIDTH; ?>px;
}
#header h1 a{color:#<?php header_textcolor();?>;}
</style>
<?php
}

That’s the very minimum for styling the header. All it does is set the header styles you defined earlier. Notice the closing PHP tag before the styles start and the opening PHP tag after the style ends.

3. Admin styles

You’ve styled the header for the web site itself, but there’s a little bit more to do still. You see, WordPress allows the user to preview their changes in the admin panel, so you have to set some styles for that as well. You can use (almost) the same code as before, but make sure to add any code that you have in your regular style sheet that applies to the header so that they admin preview and the actual site display the same way. For example, the code for the theme I’m working on at the moment looks like this:

function admin_header_style() {
?>
<style type="text/css">
#headimg{
background:#ffffff url(<?php header_image() ?>) bottom center no-repeat;
height: <?php echo HEADER_IMAGE_HEIGHT; ?>px;
width: <?php echo HEADER_IMAGE_WIDTH; ?>px;
text-align:center;
text-transform:uppercase;
}
#headimg h1{font-size:2.5em; padding:25px 0 0 0; margin:0 0 15px 0;}
#headimg h1 a{border-bottom:1px solid #dddddd; color:#444444; text-decoration:none;}
#headimg p{color:#777777; font-size:1.2em;}
</style>
<?php
}

The most important thing to note is the function name. Make sure it’s different than the name of the first function. Other than that, just use the styles from the first function along with any header related styles you have in your stylesheet.

4. Add it to the theme

Finally, you need to alert the theme about all the work you just did, so it can use all that code you wrote:

if ( function_exists('add_custom_image_header') ) {
add_custom_image_header('header_style', 'admin_header_style');
} 

5. Test it out!

Now you can save your functions.php file and go to your WordPress admin panel. Go to Appearance>Custom Header and test your new creation!

If you have any questions or comments about the process, leave a note below.

The Sanitary WordPress Theme

Update: Version 0.2 is now available.

I’ve been thinking for quite a while now about creating a blank WordPress theme as a starting point for myself as I develop new sites. I’ve gotten tired of stripping down full themes or reworking some of the other blank themes available. What I wanted was a theme with no formatting, no bells, no wistles, and no work to be done before building a new theme. There is one exception though. I don’t want to have to write all my typographical styles out each time so I added a stylesheet for type (it’s in a seperate stylesheet, so if you’d rather write your own, just get rid of the “import” line in the style.css file).

I based this theme off the Whiteboard theme by Brian Purkiss. He did a great job breaking the theme down to its most basic components. I stripped it down just a little bit more and cleaned up some code so it would validate. I borrowed my typography (with a few changes) from the SenCSs framework by Kilian Valkhof.

This theme is meant to be used. Use it for personal projects. Use it for commercial projects. Use it in whatever way you’d like.

If you find an error or have a suggestion, please mention it in the comments. I’d love to get some feedback as to what you like or dislike about this theme as a starting point for your own designs. I’m definitely open to making changes. This is just the 0.1 release. If you use it in a project, I’d love to see what you created. Feel free to leave a link in the comments. Enjoy!

Download Sanitary

  • PublishedJune 16, 2009
  • Posted InThemes

Fighting Blog Spam with Akismet

It’s been about a week and a half since I started this blog and I’m beginning to get spam comments as well as pingbacks from blogs that are just posting the first paragraph of my posts. Since I don’t want to have to moderate each individual comment, especially as the site grows, today I’m going to activate the Akismet spam filtering plugin that comes with WordPress. The Akisment plugin requires an API key from wordpress.com. As long as you’re not making more than $500/month from your personal blog, you can get an API key for free by signing up for a wordpress.com account.

1. Sign up at wordpress.com

If you don’t already have a wordpress.com account, you’ll need to go sign up. If you do, just skip to step two.

2. Retrieve your API key

Sign in to wordpress.com and click My Account>Edit Profile. Your API key will be listed at the top of the page. Copy the API key, you’ll need it in a minute.

3. Activate Akismet

Login to WordPress on your website (not wordpress.com) and click Plugins. Find Akisment and click Activate (it’s on the right). You will get a message at the top of the page saying “Akismet is almost ready. You must enter your WordPress.com API key for it to work.” Go ahead and click enter your WordPress.com API key.

4. Enter your API key

Enter the API key you copied earlier into the textbox. I also chose to to check the “Automatically discard spam comments on posts older than a month” checkbox as well. I don’t see a point in letting them take up space in the database. Click Update Options and you should get a message saying “Your key has been verified. Happy blogging!”

So… Happy blogging!

WordPress and SEO

And now for the topic of search engine optimization (SEO). As I mentioned last week, as I build this blog you’re reading I’ll write about everything I’m doing to it. Well today I’m working on improving its SEO. There internet is full of information on SEO and you could spend months or even years trying to figure it all out. I’ll start out with the basics of how SEO works and then give some practical examples of how I’m improving my SEO and how you can to.

1. What is SEO?

Search engine optimization is the process of building your website in such a way as to give it the best possible chance of being listed highly in the major search engines. According to Jason Geiger, the top search engine position gets over 40% of the clicks for any given search phrase. So if you want traffic flowing to your blog (and who doesn’t?) it pays to be the top ranked listing for something that people are actually searching for (I’ll discuss how to find out what people are searching for in a later post). But how do you do that?

2. Types of SEO

There are two types of Search Engine Optimization. The first is on-page SEO. This involves only what you have on your site or page. This is the easier of the two types of SEO to improve, since you are in control of what you put on your pages. The second type is off-page SEO and it deals with links to your site and what people are saying about you. You don’t have as much control over off-page SEO. Today we’re going to deal primarily with on-page SEO and how we can improve SEO within WordPress.

3. What do search engines look for?

Search engines judge importance much like humans. If you were attempting to find out in a short amount of time exactly what an article was about, you would read the title and headings, right? So do search engines. They also look at the page URL. For example, something like:

http://alexmansfield.com/wordpress/changing-wordpress-widgets

gives a much better indication of what the post is about than the WordPress default URL:

http://alexmansfield.com/?=13

We’ll look at how to change that in a few minutes. There are also a couple hidden fields specifically for search engines (description and keywords). Although they don’t matter like they once did (because they made it too easy to lie to the search engines) it’s still a good idea to use them properly. Now let’s get to work.

4. The All in One SEO Pack

The All in One SEO Pack is a WordPress plugin designed to make basic search engine optimization tasks easy. You don’t have to know any HTML or other technical gibberish. It gives you the option of customizing your title, description, and keywords. The title is what goes in the title bar of your web browser. Whenever you write or edit a post, scroll down to the very bottom of the page and you’ll find SEO options.

wordpress-and-seo-1

Here you can make sure that your title, description, and keywords are all present and accounted for.

5. Permalinks

I already posted a tutorial on improving the permalink structure in WordPress when I updated mine a few days ago, but I’ll give a brief overview here as well. Here’s the WordPress default I mentioned earlier:

http://alexmansfield.com/?p=123

That’s just not very informative. I prefer to have the URL display the category and then the post name. For example:

http://alexmansfield.com/seo/wordpress-and-seo

To accomplish this, go to  Settings>Permalinks and paste /%category%/%postname% in the Custom Structure field and click Save Changes.

6. Slugs

The slug is just the Title of the post as it shows up in the URL. For example, by default, the slug for this post would be wordpress-and-seo which would make the full URL to this post (due to our /%category%/%postname% permalink structure):

http://alexmansfield.com/seo/wordpress-and-seo

Not bad. However, if I were to name this post Ways to Increase Search Engine Optimization in WordPress things would get ugly:

http://alexmansfield.com/seo/ways-to-increase-search-engine-optimization-in-wordpress

Thankfully WordPress has a simple way of editing your slug, and it’s found just below the title box.

wordpress-and-seo-2

Click Edit and give your post an elegant and relevant slug.

wordpress-and-seo-3

Click Save and you should be set!

7. Sitemaps

Sitemaps are a simple way of letting search engines know about all the pages on your site so they can make sure to index all of them. Keeping a sitemap up to date by hand would be quite a chore, so I’m installing a WordPress plugin to take care of it for me. I’ve chosen the Google XML Sitemaps plugin by  Arne Brachhold. Install it just like any other plugin and then go to Settings>XML-Sitemap. If no sitemap has been created yet, there will be a link at the top to build one the first time. You can also adjust how often a new sitemap is generated, whether the search engines should be notified of a change, and more. Once a sitemap has been generated, the settings page will give you an overview of the last sitemap it generated.

wordpress-and-seo-4

8. Duplicate content

I didn’t mention at the beginning that search engines don’t like duplicate content. Unfortunately due to the way WordPress works, each post can be found at a number of different URLs, causing the appearance of duplicate content. Once again, I’m going to use a plugin to help fix this issue. This time it’s the Robots Meta plugin. You’ll find the settings for this plugin under Plugins>Robots Meta. It has quite a list of options, but each one has a nice explanation and often a suggestion or two about when or when not to use it.

Well that’s all for now. Do you have any other tips or tricks that you like to use to improve SEO on your blog? Please consider sharing it in the comments below.

  • PublishedJune 11, 2009
  • Posted InSEO, Themes

Changing WordPress Widgets

At the time of this writing, I’m using the Thematic Theme Framwork. I’m sure I’ll build my own theme for this blog in time, but for the moment I’m concentrating on other things. The Thematic Theme Framwork has 13 widget ready areas, which is more than plenty. I’m just going to rearrainge my sidebar today, so I’ll show you how it’s done.

1. Manage widgets

Log into WordPress and go to Appearance>Widgets. Mine looks something like this:

wordpress-widgets-1

On the left side is a list of all the available widgets. On the right side is a list of the widgets that are currently in use in the selected widget ready area.

2. Add and remove widgets

Use the drop down list at the top of the right side to select which widget ready area you want to add or remove widgets from. To add a new widget, find the one you want in the left hand column and click Add. To remove a widget that is already in use, find it in the right had column and click Edit and then Remove. Other aspects of the widget can also be changed in the Edit section.

3. Rearranging widgets

Finally, to rearrange the widgets that are currently in use, you can just drag-and-drop them into the order you prefer. It’s pretty handy. Have fun!

Installing WordPress in a Subdirectory

There are two reasons I like to install WordPress in its own folder, rather than the  root. First, I like to keep my root folder uncluttered. I don’t like a bunch of WordPress files that I’ll never be messing with getting in my way.  That’s just a matter of personal preference though. The second reason is for security. To prevent automated site scans from easily finding my WordPress files, I simply place them in a separate directory. So… here’s how you do it. It’s actually quite simple.

1. Install WordPress in a subdirectory

Just follow the instructions I gave in my post Installing WordPress Manually. Make sure you create a new directory and upload the WordPress installation files there (that’s step three in the post I just mentioned).

2. Edit the index.php file

Once WordPress is installed, download the index.php from the directory where you uploaded WordPress. You’ll need to open it up and make one small change. Find this piece of code:

/** Loads the WordPress Environment and Template */<br />
require('./wp-blog-header.php');

All you need to do is tell it how to find wp-blog-header.php in its new subdirectory. For example, here’s what the code would look like if I installed WordPress in a directory called example.

/** Loads the WordPress Environment and Template */<br />
require('./example/wp-blog-header.php');

Notice how I added /example just before /wp-blog-header.php. So just add the name of your directory in place of example and that’s all the code editing you have to do.

3. Upload the new index.php file

Now that you’ve made the necessary change to your index.php file, it’s time to upload it to your root directory. Make sure you delete the old index.php file in your WordPress directory.

4. Tell WordPress what you did

Finally, you need to let WordPress know about the change. First, log into WordPress. The login page will still be at the old URL (for example http://alexmansfield.com/example/wp-login.php not http://alexmansfield.com/wp-login.php). Go to Settings>General and change the Blog Address field (for example, from http://alexmansfield.com/example/ to http://alexmansfield.com/). Save your changes and that should do it!

If you have any questions, please ask them in the comments section below.

Changing Permalinks in WordPress

This will also be in my upcoming post on improving SEO in WordPress, but since I promised to write about everything I’m doing on this blog, I’ll make a separate post about it now. Permalink structure refers to the way URLs are formed within WordPress. For example, the default permalink structure in WordPress looks like this:

http://alexmansfield.com/?p=123

Not very pretty, useful, or search engine friendly. A human can’t read “?p=123″ and tell what the page is about and neither can a search engine. Thankfully, WordPress makes it easy to change the way your URLs look. Just login to WordPress and go to Settings>Permalinks. First, there are some built in options, such as:

http://alexmansfield.com/2009/06/sample-post/

These are an improvement over “?p=123″ but they’re still not that great. Very few people will include a date in their search, so the date is pretty much just wasting space in your URL. But you don’t have to settle for these built in options. WordPress also gives you the opportunity to specify your own permalink structure. Here’s what I use:

/%category%/%postname%

That displays the category that the post is assigned to, followed by the name of the post. Short and sweet. Unless of course, you use categories like “This-is-the-best-category-on-my-website-and-you-should-read-all-about-it.”

Do you have a different permalink structure that you prefer. Tell us why in the comments section!

Six Steps Toward Securing WordPress

WordPress is a great publishing platform, but there a few steps that should be taken to make it more secure. Here are 6 of the best.

1. Delete the user “admin”

Every WordPress installation automatically generates a user account with the username admin. I’ll admit this is a logical username, but EVERY blog having the same username is not the best idea. Imagine someone trying to compromise your blog. What’s the first username they’re going to attack? That’s right, the admin. So, go to Users>Add New and create a new user for yourself. Make sure to set your role to administrator. Then log out and log back in as the user you just created. Now go back to the Users page and delete the admin account. Problem solved.

2. Use secret keys

According to wordpress.org,

In simple terms, a secret key is a password with elements that make it harder to generate enough options to break through your security barriers. A password like “password” or “test” is simple and easily broken. A random,  unpredictable password such as “88a7da62429ba6ad3cb3c76a09641fc” takes years to come up with the right combination.

WordPress stores the secret keys in the wp-config.php file in your WordPress directory. You need to download a copy of your wp-config.php file in order to add your secret keys. Open the file and scroll down until you find something like this:

define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
define('NONCE_KEY', 'put your unique phrase here');

Now, you can come up with your own unique phrases if you’d like, but I prefer to use the WordPress secret-key generating service. You won’t ever have to remember these keys so they can be long and complicated (actually, they should be long and complicated). To use the key generating service that WordPress provides, go to https://api.wordpress.org/secret-key/1.1/

You’ll see something that looks like this:

define('AUTH_KEY',        '|g_-s~>*qlxC|7x>~IYb180rU6u-r}D#dG>Q[GHCR~ql#l.7-noM5n6=E!.~SEDs');
define('SECURE_AUTH_KEY', ':kN}%tH6,O!fBpO|(u3o3~|ve/_q4:He|7Gm@)k(IIGGb}t`qAqD3-vV t/|I+85');
define('LOGGED_IN_KEY',   ' ,%4j5%9-v6hEa6THQN,+2CjPywX-HxhLj|vYSRb*7ra.Wl7RG%-Hoy4Ln0ZhTf^');
define('NONCE_KEY',       ']{nb6+C)8u&amp;amp;amp;?+e8necJSKzt)e0`x8L vQue!sV!o}d-F<v%DNhZKDv7fFLRH/9]L');

Copy the entire thing and use it to replace the section in wp-config.php that needed the secret keys. Save the file and upload it back to your website in place of the old file.

Please note: if you logged in to your WordPress administration panel before changing they keys, you’ll have to log back in.

3. Turn off directory browsing and protect the wp-config.php file

Don’t let people snoop around your site where they weren’t intended to be. Use an .htaccess file to protect the portions of your website that weren’t meant for public viewing. For example, WordPress has a directory where it stores its plugins. No one needs to look at what plugins you have installed (unless they’re looking for people who are using a plugin with a known vulnerability). So to protect yourself, create a new file and name it .htaccess (yes, it starts with a period) and place the following code in it:

# turn off directory browsing
Options All -Indexes

# protect wp-config.php
<files wp-config.php>
Order deny,allow
deny from all
</files>

Upload the file to the same directory as your wp-config.php file. This protects both your directories and the wp-config.php file that holds important database details.

4. Limit login attempts

No matter how strong a password is, it can be guessed with enough tries. The Limit Login Attempts plugin solves this problem nicely. To protect your site, download the Limit Login Attempts plugin (the download link is at the very bottom of the page), unzip it and upload it to your plugins directory (wp-content/plugins). Now log into WordPress and go to the Plugins page. Find Limit Login Attempts and click Activate (on the far right). You can change how many login attempts are allowed and make other changes by going to Settings>Limit Login Attempts.

5. Encrypt your logins

By default, WordPress login information (username and password) are transfered in plain text. You can use the Chap Secure Login plugin to encrypt your password for increased security. Plugin installations are pretty much all the same, so just follow the same steps as before (download, unzip, upload to plugins folder, activate from admin panel).

Please Note: The first time you try to login after installing this plugin, the login will fail. This is normal. After the first attempt, everything should go back to working properly. As a side note, this failed login will give you a change to see the Limited Login Attempts plugin in action (it should tell you how many tries you have left).

6. Don’t display what version of WordPress you’re using

If there is a known vulnerability with a certain version of WordPress, you don’t want to broadcast to the world that your site contains that vulnerability. WordPress automatically displays the version number as a comment in the header code, but we can change that quite easily. Just add this line to the functions.php file of your WordPress theme if you’re theme doesn’t suppress the version number already.

remove_action('wp_head', 'wp_generator');

Also, if you uploaded the readme.txt file that came with WordPress, you should delete it, since it also contains the version number.

Bonus: Scan you site for vulnerabilities

There is a WordPress plugin developed by the guys over at blogsecurity.net that will scan your site for known vulnerabilities. Do yourself a favor and check your blog.

That’s it for now. Do you have any other techniques that you use to secure your WordPress sites? Please post them in the comments. Thanks.

  • PublishedJune 8, 2009
  • Posted InSecurity

« Older Entries