Simple PHP Redirect in WordPress

Note: This post was originally written for my blog over at sackclothstudios.com. However, with the changes I’m making to that site, I figured the post would be of more use here on this site.

Update: there is also a WordPress function for redirects: wp_redirect()

Sometimes when using WordPress you want to include a non-Wordpress page in your main navigation while still maintaining the simplicity of the wp_list_pages() function. I know there are plugins that do this type of thing, but many of them are just overkill. I just needed one non-Wordpress page on my menu, so here’s what I did. First, I created a page from within WordPress and gave it a heading but left the body blank. My page was called “Purchase” but you can name it whatever you’d like. This is the name that will show up in your navigation menu. Then I went to the header.php file of my theme and added this at the top:

if(is_page('purchase')){
header("HTTP/1.1 301 Moved Permanently");
header("Status: 301 Moved Permanently");
header("Location: http://www.example.com/");
header("Connection: close");
exit(0); // Optional, prevents any accidental output
}

Obviously, you’ll want to change the if statement to check for the blank page that you set up. Then change “http://www.example.com/” to whatever page you want the redirect to point to. Make sure that you put the code at the very top of the header.php file. If something else comes before it, it won’t work.

I first found this PHP redirect on  Steven Hargrove’s blog.  He gives examples of this in a number of different languages. However, I adapted it to WordPress and added the ” header( “Connection: close”);” line to get it working properly. I’d love to hear how you solve this little WordPress problem. If you have a different solution, please leave a comment below with a brief explaination. Thanks.

Update #1: If you want to make a temporary redirect (302), rather than a permanent one (301) use the code below:

if(is_page('purchase')){
header("Location: http://www.example.com/");
header("Connection: close");
exit(0); // Optional, prevents any accidental output
}

Update #2: Algen asked if it was possible to create a delayed redirect. It is possible, using either PHP or HTML. As Dhruv pointed out in the comments, PHP handles it like this:

header( 'refresh:5;url=wherever.php' );

If you’d prefer to use HTML, it can be done like this:

<meta http-equiv="refresh" content="10;url=http://www.example.php">

Sanitary Theme 0.2

Update: Version 0.3 is now available.

It has been 10 months to the day since I released Sanitary 0.1, a clean starting point for developing WordPress themes. An update is obviously overdue, so even though it will need to be updated again as soon as WordPress 3.0 comes out, I’m releasing Sanitary 0.2. It is still a work in progress, but as you can see from the changelog, there have been quite a few changes under the hood. The change that I’m most excited about is the move to HTML5, with support for even Internet Explorer (Thanks to Remy Sharp’s HTML5 enabling script).

Here’s the changelog:

deleted
– searchform.php
– categories.php
– archive.php
– archives.php

functions.php
– added thumbnail support

single.php
– changed h2 to h1 (single.php)

search.php
– replaced the seachform call with a form

404.php
– replaced the seachform with a widget area

archives.php
– replaced the seachform call with a form

archive.php
– replaced the seachform call with a form

comments.php
– added anchor tag to comments heading to allow links to the comments section (url.com/example.html#comments)
– added <small> tags around allowed tags
– removed double reference to number of comments
– changed ids to match names for comment form
– added label for comment textbox
– removed the “(required)” message from the “Name” and “Mail” labels (Not sure about this decision. Input welcome.)
– Changed “Mail” label to “Email”

all over the place
– added underscores to many ids (.post_meta, .post_navigation #comments_form)
– converted to html5 and included javascript to allow older browsers to render new tags properly
(http://remysharp.com/2009/01/07/html5-enabling-script/)

Version 0.2 is no longer available. Version 0.3 is now available.

WordPress Single Category Search

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

  • PublishedSeptember 7, 2009
  • Posted InWordpress

WordPress Plugin: Latest Posts 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

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

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!

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!

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. Feel free to leave the old index.php file in your WordPress directory, as this will prevent users from looking at the contents of 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.

« Older Entries Newer Entries »