Wordpress Single Category Search

Written on September 7, 2009 at 9:39 am, by alexmansfield

custom-search

Sometimes it comes in handy to make the search form on a blog only return results from a single category. It’s actually quite simple.

1. Find the category ID

First we need to find the ID of the category that we want to search. We can find that by going to Posts>Categories and hovering over the category we want to search in the categories list on the right side of the page. When we hover the mouse over a category, we’ll see something like this in the status bar (usually the bottom left corner of the browser):

…/wp-admin/categories.php?action=edit&cat_ID=3

As you can probably see, the 3 at the end is the category ID. That number is all we need to know.

2. Edit the searchform.php file

We just need to find this line in the searchform.php file of the theme:

<form method="get" id="searchForm" action="<?php bloginfo('home'); ?>/">

and add this hidden field immediately after it:

<input type="hidden" name="cat" id="cat" value="3"/>

3. Apply the category ID

Now we need to make sure that we change the value of the hidden field to the category ID we found in step one. For example, if the category we chose had an ID of 12, then the hidden field would look like this:

<input type="hidden" name="cat" id="cat" value="12"/>

It’s that easy! If you have any questions, feel free to post them in the comments section below.

Image by rockmixer

Wordpress Plugin: Latest Posts by Author

Written on August 11, 2009 at 4:52 pm, by alexmansfield

latest-by-author

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.2
Author URI: http://alexmansfield.com/
*/

function latest_posts_by_author($array) {
extract(shortcode_atts(array('author' => 'admin', 'show' => 5), $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="'.$numpost->guid.'">'.$numpost->post_title.'</a></li>';
$i++;
if($i == $show){
break;
}
}
$html .= '</ul>';

return $html;
}

add_shortcode('latestbyauthor', 'latest_posts_by_author');

?>

Menus Hiding Behind Flash

Written on August 6, 2009 at 2:07 pm, by alexmansfield

hiding-menus

I ran across an issue today where a drop down menu was dropping behind a flash object rather than in front. It seems to be a pretty common problem, so I thought I’d share the solution.

1. Start with the embed code

To make sure that the drop-down menu appears above the flash object, there’s a single parameter we need to add to the embed code. First of all, here’s what a normal YouTube embed code looks like:

<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/Z19zFlPah-o&amp;amp;amp;hl=en&amp;amp;amp;fs=1&amp;amp;amp;rel=0"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed
src="http://www.youtube.com/v/Z19zFlPah-o&amp;amp;amp;hl=en&amp;amp;amp;fs=1&amp;amp;amp;rel=0"
type="application/x-shockwave-flash"
allowscriptaccess="always"
allowfullscreen="true"
width="425" height="344">
</embed>
</object>

2. Add a parameter

We’ll need to add the parameter in two places. First we’ll need to add the following code after the other param fields (or before, it doesn’t really matter).

<param name="wmode" value="transparent">

Next, wmode=”transparent” needs to be added to the actual embed tag like this:

<embed
wmode="transparent"
src="http://www.youtube.com/v/Z19zFlPah-o&amp;amp;amp;hl=en&amp;amp;amp;fs=1&amp;amp;amp;rel=0"
type="application/x-shockwave-flash"
allowscriptaccess="always"
allowfullscreen="true"
width="425" height="344">
</embed>

That’s it!

So all together, this is how it should look when we’re done:

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="344" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">
<param name="allowFullScreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="src" value="http://www.youtube.com/v/Z19zFlPah-o&amp;amp;amp;hl=en&amp;amp;amp;fs=1&amp;amp;amp;rel=0" />
<param name="allowfullscreen" value="true" />
<param name="wmode" value="transparent" />
<embed
type="application/x-shockwave-flash"
width="425"
height="344"
src="http://www.youtube.com/v/Z19zFlPah-o&amp;amp;amp;hl=en&amp;amp;amp;fs=1&amp;amp;amp;rel=0"
allowscriptaccess="always"
allowfullscreen="true"
wmode="transparent">
</embed>
</object>

Hope that helps!

Image by Lili Vieira de Carvalho

Adding Custom Wordpress Shortcodes

Written on July 27, 2009 at 12:45 pm, by alexmansfield

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.

Week Three

Written on June 23, 2009 at 11:56 pm, by alexmansfield

three-weeks

I got a pleasant surprise today when I looked up my Google pagerank. It appears they’ve updated their ranks and this site went from a 0 to a 3. Not bad for 3 weeks. It looks like putting in the time and effort actually leads to some visible results. The results are not stunning by any stretch of the imagination, but at least I can see them. Eventually I would like to find clients through this site though, not just check my pagerank and look at pretty Google Analytics graphs.

Anyway, I’ve started submitting some of my posts to various social media outlets, but none of them bring in the traffic like Twitter, that’s for sure (at least not yet). The number of visitors grew from 12 last week to 82 this week, which was pretty substantial, at least if you look at it in percentage form (583%). I don’t think I’ll be able to keep that up :] My Feedburner subscriber count went up as well (to 9), and this time it looks like some of them are actually humans, not bots.

That’s it for now. I’ll try to give a little more in depth look at traffic sources etc. at the one month mark next week.

Super Twitter Stats with Su.pr

Written on June 20, 2009 at 11:39 pm, by alexmansfield

supr-twitter-traffic

There’s a new service from the guys over at StumbleUpon that acts as a Twitter update client, a stat counter, a URL shorter and more all rolled into one. I’ve been using it for a couple days now, and it’s pretty cool. It’s still in private beta at the moment, but they post invite codes fairly often on their Twitter feed. It was developed with input from Tim Ferris of “The Four Hour Work Week” fame and it promises to take care of many of the issues that come with promoting your blog on Twitter. According to StumbleUpon, it is a…

…brand new short url service designed to drive more traffic to your site. Su.pr provides real time analytics for all of your generated links as well as the ability to post your Su.pr links to other social media services such as twitter and facebook.

Not only does it count how many clicks you recieve from Twitter, but also from StumbleUpon itself, which is handy. It keeps track of when you posted and how many clicks you recieved, so over time it can suggest when the most profitable time to tweet would be. What? You’ll be away from your computer at the most profitable tweeting time? No problem. Just schedule your tweet for later. Here’s a screenshot.

supr-twitter-traffic-2

On the URL shortening side, the best features are still in the pipeline. The plan is to allow blog owners to use their own domain name rather than su.pr domain in the shortened URLs. They’re also going to allow site owners specify if they want a 301 redirect for SEO purposes.

All sorts of interesting things are happening with this application at the moment, so you might want to check it out.

Wordpress Custom Headers

Written on June 20, 2009 at 5:22 pm, by alexmansfield

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.

Wordpress Image Sizes

Written on June 19, 2009 at 9:37 pm, by alexmansfield

wordpress-image-sizes

By default, Wordpress has four sizes that you can choose from when displaying your images. They are:

  1. Thumbnail (150×150)
  2. Medium (300×300)
  3. Large (1024×1024)
  4. Full Size (Whatever the image dimensions are)

That’s great that they give us choices, but what if we want a diffent size? I really wanted my images to be the same width as my content, so I went searching for a way to easily do that. It just so happens that Wordpress has an option in the admin panel for changing the default sizes. Just go to Settings>Media and you can adjust sizes to your hearts content. I set my large size at 560×1024 (560 being the width of my main content area). If you want your image to always match the width of your content, make sure you set Max Height significantly larger than Max Width. That will keep pictures that are longer vertically from being trimmed smaller than the content width. That’s all for now!

Custom Wordpress Theme

Written on June 19, 2009 at 8:50 pm, by alexmansfield

custom-wordpress-theme

This theme is barely usable, but I’m tired of using someone else’s theme, so I figured I’d upload it. I built it on top of my Sanitary Wordpress theme this afternoon. It really has no features at all, and I’m not super excited about it, but at least my blog doesn’t look exactly the same as 30,000 other blogs now. I’m sure it will evolve over time.

Have any comments or suggestions regarding the design? Comment below!

Adding Google Analytics to Wordpress

Written on June 18, 2009 at 3:49 pm, by alexmansfield

Adding Google Analytics to your Wordpress blog enables you to see how many people are actually visiting your site. You can also find out where they came from, what they were searching for, what they read, and how long they stayed. There are tons of options when it comes to analytics software, but Google Analytics is one of the easiest to set up and it does everything I need (my only complaint is the lack of real time stats). Today I’ll walk you through the process of setting it up. All you really have to do is add a small chunk of Javascript to every page that you want Google to track. It is possible to manually add it to your theme, but if you were to switch Wordpress themes, your changes would be gone. So I’m going to show you how to use a plugin to add it instead. This way theme changes won’t be an issue.

1. Sign up for Google Analytics

It’s pretty straight forward. You can use an existing Google account to sign up, but it’s not required. Go here to sign up: http://www.google.com/analytics/sign_up.html. At the end of the sign up process, you will get a piece of code. We won’t actually be using all that code, but it’s not a bad idea to save it anyway (it’s not the easiest to find later on if you ever end up needing it).

2. Install a plugin

There are plenty of choices when it comes to Wordpress plugins for Google Analytics. I prefer to use Google Analytics for Wordpress by Joost de Valk. Not only has this plugin received great reviews, Joost is an active member of the Wordpress community. Download the plugin, unzip it, and upload it to your Wordpress plugins directory.

3. Configure the plugin

Login to Wordpress and go to your Plugins page. Find the plugin you just uploaded and click Activate. Now for the plugin to actually work, it needs to know your UA string. This was buried in the code that Google gave you when you signed up. However, there’s an easier way to find it. While you’re logged into Google Analytics, go to the home page by clicking the Google Analytics logo in the top left corner. The home page will list all the sites that you’re using Google Analytics on (there will just be one at this point if you’re setting up analytics for the first time). Just to the right of your domain name, there will be a number. That’s your UA string. Copy it. You’re almost finished. Now go back to Wordpress and go to Plugins>Google Analytics. There will be a warning alerting you that Google Analytics is not active because you haven’t entered your UA string. The UA string goes in the first textbox (it’s labeled Analytics Account ID).  Make sure that the Where should the tracking script be placed? option is set to In the footer. You don’t want the user to have to wait for your analytics script to run before viewing your page, so it’s best to load it in the footer. You can adjust all sorts of other settings if you want, but it isn’t really necessary. Click Update Settings and you should be on your way.

Keep in mind that Google Analytics does not give you real-time statistics, so you might have to wait a day or so before you can check on your traffic.