Category: Wordpress

Reset Your Wordpress Password

9 September, 2008 | Wordpress | No comments

If for some reason you can’t remember your Wordpress password and you can’t use the "lost your password" function that comes with Wordpress, due to problems with email, then you can use the following SQL command to reset your password.

UPDATE wp_users SET user_pass = md5('newpassword') WHERE user_login = 'admin';

This can be useful if you have a local web server that you are trying things out on before they go live on the Internet. These servers often don’t have access to email as they are just testing platforms and will therefore fail if you try to use the "lost your password" function.

This command has been tested on Wordpress version 2.6.2.

Enable Custom Field Searching With Wordpress 2.6

5 September, 2008 | Wordpress | No comments

I have previously talked about enable custom field search in Wordpress, but that involved altering the main Wordpress files, which is a big no-no.

So is there an alternative? Well, yes, otherwise I wouldn’t have bothered writing the post!

To enable custom field (also called Wordpress metadata) searching you need to set up two things.

First you need to have created a custom field (or two) and added this to a number of posts.

Next, you need to have a custom search form that has the name of the field set as the name of an input box. You don’t even need the normal s input box that Wordpress uses as default.

Open up your template functions.php file and add in the following three lines of code.

add_filter('posts_join','search_metadata_join');
add_filter('posts_where','search_metadata');
add_filter('posts_groupby','search_meta_groupby');

This adds three callback filters to Wordpress at run time. The posts_join will add the meta table into our query so that we can work with it. The posts_where will be the main function where all of our where clauses will be build. Finally, posts_groupby will stop multiple posts appearing for the same term. All we have to do now is include the queries we need in order to enable custom field searching. I will do each of the callback functions in the order they appeared above.

function search_metadata_join($join) {
 global $wp_query, $wpdb, $wp_version;
  // add in check for older versions
 if($wp_version >= '2.3'){
  $join .= " LEFT JOIN $wpdb->postmeta AS m ON ($wpdb->posts.ID = m.post_id) ";
 }else{
  $join .= "LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
 }
 
 return $join;
}

The search_metadata() function has a array variable called $metaVars. This contains an array of the names of the custom fields that you want to search through. Each item in the array is checked to see if it has a value, and if it does it is included in a string called clause. The function is set up to allow for any of the custom fields being true, which is what I wanted it do to.

function search_metadata($where) {
 global $wp_query, $wpdb, $wp_version;
 
 $metaVars = array('custom1','custom2');
 $where .= ' AND (';
 foreach($metaVars as $metaValue=>$metaKey){
  if(!empty($_GET[$metaKey])){
   if($wp_version >= '2.3'){
    $clause .= " OR (m.meta_key = '".$metaKey."' AND m.meta_value LIKE '%".$wpdb->escape($_GET[$metaKey]) . "%') ";
   }else{
    $clause .= " OR (meta_key = '".$metaKey."' AND meta_value LIKE '%" . $wpdb->escape($_GET[$metaKey]) . "%') ";
   }
  }
 }
 $where .= substr($clause,3).') ';
 return $where;
}

Finally, here is the search_meta_groupby() function. I pulled this from the wordpress.org site and adapted it slightly.

function search_meta_groupby( $groupby ){
 global $wpdb;
 
 // we need to group on post ID
 $mygroupby = "{$wpdb->posts}.ID";
 if( preg_match( "/$mygroupby/", $groupby )) {
  // grouping we need is already there
  return $groupby;
 }
 
 if( !strlen(trim($groupby))) {
  // groupby was empty, use ours
  return $mygroupby;
 }
 
 // wasn't empty, append ours
 return $groupby . ", " . $mygroupby;
}

All this is designed to get you started in creating custom field Wordpress searching. You might have to tweak the code involved here before you get it working.

Display Certain Categories Within Wordpress

29 August, 2008 | Wordpress | No comments

If you want to display a Wordpress front page in a new or interesting way by splitting the categories into sections, or by not displaying certain categories at all then you can use the query_posts() function. This function comes as part of Wordpress and allows you to override the queries that are being executed behind the scenes. This basically controls what posts are seen by "the loop". In order for the function to work it must be called before "the loop", look out for this line (or similar):

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

And put the call to query_posts() before that. You will need to give it certain parameters in order to do something.

So what can you do with this function? Well all sorts of stuff, but for this post we are just interested in getting different categories out, so lets concentrate on that.

With regards to parameters the function takes the following arguments. Notice that the last three have a double underscore.

  • cat
  • category_name
  • category__and
  • category__in
  • category__not_in

The most basic thing you can do is pass the category ID with the parameter cat. The following bit of code will get those posts in category 3
query_posts("cat=3");

You can do this the other way around as well by adding a - to the category ID and therefore getting everything but that category.
query_posts("cat=-3");

You can pass multiple category ID’s using commas. The following code will get categories 2,3 and 8.
query_posts("cat=2,3,8");

Excluding categories can be done in the same way.
query_posts("cat=-2,-3,-8");

Using category ID’s can be a bit confusing, but luckily you can also pass the category name. Note that you can’t include multiple categories this way, so this is only useful if you want a single category to be displayed.
query_posts("category_name=Wordpress");

To display posts that appear in multiple categories you can using the category__and parameter. The code here will display posts that appear in category 3, category 8 AND category 9. You can add as many as you like to this list.
query_posts(array("category__and" => array(2,8,9)));

The category__in parameter works in just the same way as a comma separated list used with the cat parameter, it is just a different way of doing the same thing. The following code will get posts in categories 1, 2 and 3.
query_posts(array("category__in" => array(1,2,3)));

The category__not_in parameter works in the opposite way from the category__in parameter. The following code will get posts that are not in categories 5 and 6.
query_posts(array("category__not_in" => array(5,6)));

It is also possible to change the order that that posts are printed out in. The default is to have the posts printed out in descending order based on the published date. To change this you can just add in the parameter order followed by ASC to make the posts sort in ascending order.
query_posts("cat=-3&order=ASC");

You can explicitly set the descending order by using the DESC parameter argument.
query_posts("cat=-3&order=DESC");

Try a few combinations yourself. It is also possible to have different sections by calling the query_posts() function a second time, just remember that you need another loop in order to print out the posts. To simplify things your can split out the loop into a separate file (I called mine post.php) and include it will the following snippet.
<?php include (TEMPLATEPATH . "/post.php"); ?>

You can then write query_posts(), include(), query_posts(), include(), query_posts(), include().

Custom Search Form With Wordpress Search Widget

30 July, 2008 | Wordpress | No comments

When adding a search form to your Wordpress blog you will want to have control over what sort of form is displayed. It is possible to override the search form created by the widget function without having to go into the /wp-includes/widget.php file and editing the wp_widget_search function. Here is the function that is present in Wordpress 2.6.

function wp_widget_search($args) {
 extract($args);
 $searchform_template = get_template_directory() . '/searchform.php';
 
 echo $before_widget;
 
 // Use current theme search form if it exists
 if ( file_exists($searchform_template) ) {
  include_once($searchform_template);
 } else { ?>
  <form id="searchform" method="get" action="<?php bloginfo('url'); ?>/"><div>
  <label class="hidden" for="s"><?php _e('Search for:'); ?></label>
  <input type="text" name="s" id="s" size="15" value="<?php the_search_query(); ?>" />
  <input type="submit" value="<?php echo attribute_escape(__('Search')); ?>" />
  </div></form>
 <?php }
 
 echo $after_widget;
}

Notice that the first thing the function tries to do is load a template file called searchform.php, and if this doesn’t exist the function prints out a standard search form. That is it basically. If you want to override the search form created by this function then just create a file called searchform.php in your template directory and create a search form inside this file. The form must have the following:

  • The action of the form should go to the home of the blog. So if your blog is located at domain.com/blog then the action should go to there.
  • The method of the form should be get, but the form will also work with a post method.
  • A text input box must be present and this must have the name of s.
  • For good search form usability you should print out the search query in the text field of the form. This can be done with the function the_search_query(), which will print out the search query, if there is one.

There are many different ways to create a search form. I found these two in two different templates, created by different people.

<h2>Search</h2>
<form method="get" id="searchform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="searchbox">
<label for="s">Find:</label>
<input type="text" value="<?php echo wp_specialchars($s, 1); ?>" name="s" id="s" size="14" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>

This one will print out a little bit of JavaScript in the text box.

<div id="search">
<form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">
<div><input type="text" value="search..." name="s" id="s" onfocus="if (this.value == 'search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'search...';}" />
</div>
</form>
</div>

They both seem to work quite well, but I would advise that any search form you create should be copied from the original and modified. This is usually the best practice with Wordpress themes as the Wordpress documentation can be a little thin on the ground (or hidden) and their developers tend to use the best functions available.

Getting Started With Wordpress Templates

29 July, 2008 | Wordpress | No comments

If you are setting up a Wordpress blog the chances are that you will be looking into modifying the default theme to be something a little more customised to your site. Theme development can be as complicated or as simple as you want, or are capable of doing.

Wordpress themes are stored in the folder wp-content/themes/, each theme being stored in it’s own directory.

The basic theme must contain two basic files, the main control is done from a file called index.php and a file called styles.css, which is also needed to allow you to display the theme within the admin section of Wordpress. If you don’t want to use the styles.css file then this is fine, but it should be present and contain the following lines.

/**
* Theme Name: Your theme name
* Theme URI: www.talkincode.com
* Description: A theme designed by the guys at talkincode.com
* Author: Tech
* Author URI: talkincode.com
* Version: 1.0
*  
* General comments can go in this space.
*/

This is all integrated into your Wordpress administration section under themes. If you want a screenshot to appear as well as the description then create a file called screenshot.png, make it 300 pixels wide by 225 pixels high and put it in the same folder as the rest of the files.

There is also a file called functions.php in which you can define custom functions that can be used in your template. This includes, but is certainly not limited to, adding a widget definition. The functions file is loaded right at the start of the template and is looked at when viewing the administration section of your site. Any code kept in the functions.php file is called rather like a plugin and so it is possible to write plugin-like code in this file and have it act accordingly.

Other files can be included very easily.

The header file will contain the HTML at the top of the page (including styles and meta tags) and will get included via the get_header() function like this.
<?php get_header(); ?>

The footer file will contain the HTML at the bottom of the page (including copyright and site tags) and will be included via the get_footer() function like this.
<?php get_footer(); ?>

The sidebar of the site can be included using the get_sidebar() function. This can contain a widget call or
<?php get_sidebar(); ?>

If anything else is to be included from the template folder then the TEMPLATEPATH constant can be used in conjunction with a include() function call.
<?php include(TEMPLATEPATH . '/searchform.php'); ?>

Wordpress will automatically recognise certain files depending on what action is being taken. For example, when looking at a single post or page the single.php file is used instead of the index.php file to load the template. If this file doesn’t exist then it uses the standard index.php file.

Also, if the user clicks on a link for a category, Wordpress will load the category.php file. If this is not present then Wordpress tries to load a file called archive.php. If both of these files are not present then Wordpress load the main index.php file instead.

A files called 404.php is also used when a 404 response is needed. This file is called automatically during a 404 response and does not require any .htaccess modifications.

A lot of default tags are available for you to use if you don’t want to hard code things into your template. For example, to include the name of your blog in your template you can use the following code.

<?php bloginfo('name'); ?>

In addition to the name tag the tags description, url, admin_email and version are also available.

The Loop is used by Wordpress to display each post in turn. The loop takes the following format.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
// the contents of the post can be displayed here
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

There are a number of different tags that can be placed within the loop to print out different information. For example, to print out the content you just need to call the the_content() function.

<?php the_content(); ?>

The best way to get acquainted with Wordpress templates is to simply make a copy of the default template that comes with Wordpress and edit it to suit your needs. In this way you can figure out how things work, why the template is set up as it is and what files do what.

The following links go to specific pages within the Wordpress documentation and should also help out.

codex.wordpress.org/Stepping_Into_Templates: The Wordpress documentation on getting started on templates.

codex.wordpress.org/Stepping_Into_Template_Tags: A list of the different tags available for both the bloginfo() function and within the loop.

codex.wordpress.org/Template_Hierarchy: This page looks at the files available for a theme and when they are called.

codex.wordpress.org/Theme_Development: The Wordpress documentation on developing themes.

codex.wordpress.org/Site_Architecture_1.5: The different files available for templating. Although this document was written with version 1.5 the content seems valid.

codex.wordpress.org/Function_Reference: A reference document for all of the functions available in Wordpress. Although some don’t matter for template development this is still a good resource for template functions.

codex.wordpress.org/The_Loop: Help on The Loop.

codex.wordpress.org/Using_Themes: Help on using themes.