How to: Create an Ajax-based Auto-completing Search Field for your WordPress Theme

Why not helping your visitors to find what they’re looking for on your blog, by using a cool auto-completion on your search field? To do so, we’ll use WordPress tagcloud, php and ajax.

Please note that even if this code is fully functional, this is an experimentation, and the SQL query isn’t really optimized.

The idea

We will use tags as a list of keyword to suggest to the readers.

When someone will start to type on the search field, we will use Javascript to send a request to a php page which will do the following SQL request SELECT * FROM matable WHERE ‘name’ LIKE ‘$search%’. Via Ajax, we’ll send back the request results to our page, and display it to the visitor.

First part: PHP

The first thing to do is to create a php page. This page will send a request to our WP database and display the tags as a html unordered list.
<?php
if (isset($_POST['search'])) {
$search = htmlentities($_POST['search']);
} else $search ='';
$db = mysql_connect('localhost','root',''); //Don't forget to change
mysql_select_db('wp', $db); //theses parameters
$sql = "SELECT name from wp_terms WHERE name LIKE '$search%'";
$req = mysql_query($sql) or die();
echo '<ul>';
while ($data = mysql_fetch_array($req))
{
echo '<li><a href="#" onclick="selected(this.innerHTML);">'.htmlentities($data['name']).'</a></li>';
}
echo '</ul>';
mysql_close();
?>

This code is simple: It receive a POST parameter (The letter(s) typed in the search field by the visitor) and then sends a request to our WP database in order to gets all tags starting with the letter(s) typed in the search box.

Part two: Ajax

Now it’s time to start the client-side programming. We need to code 4 Javascript functions in order to make our auto-completion work:

  • Function ajax() will create a XMLHTTPRequest object.
  • Function request() will send an Ajax request to our gettags.php file.
  • Function return() will return gettags.php contents.
  • And the selected() function will update the search field.

Here’s our gettags.js file and the 4 functions needed:
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "wp-content/themes/openbook-fr/gettags.php");
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}

Part three: Editing your theme

Now that we have our php and javascript ready, we can edit the searchform.php file from your WP theme:

Your searchform.php file should look like this:
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>

We have to add a div, which will display the received data from the request, as well as a Javascript event on the search form:
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" onkeyup="request(this.value);"/>
<input type="submit" id="searchsubmit" value="Search" class="button" />
</div>
<div id="tag_update"></div>
</form>

Final part: CSS

Due to the fact that every theme use different color schemes, this is only an example. Anyways, I thought it could be a good start:
#tag_update {
display: block;
border-left: 1px solid #373737;
border-right: 1px solid #373737;
border-bottom: 1px solid #373737;
position:absolute;
z-index:1;
}
#tag_update ul {
margin: 0;
padding: 0;
list-style: none;
}
#tag_update li{
display:block;
clear:both;
}
#tag_update a {
width:134px;
display: block;
padding: .2em .3em;
text-decoration: none;
color: #fff;
background-color: #1B1B1C;
text-align: left;
}
#tag_update a:hover{
color: #fff;
background-color: #373737;
background-image: none;
}

That’s all. You now have a very nice auto-completing search form! If you have any questions, feel free to leave a comment below.

  • Leave a Comment
  • Parsing and Hacking External RSS Feeds in WordPress

    It’s a little known fact that WordPress contains it’s own RSS parser, and you can use it to your advantage to make custom dynamic pages!

    This is a tutorial on how to take an ordinary RSS feed, parse it using WordPress’ internal RSS parser, and then create dynamic pages with it. I’m not talking about being a scraper, creating a splog, or doing anything spammy at all. I’m talking about creating added value for visitors and your blog while making money. We all know what a “splog” is. It’s a “spam blog”…or someone who takes RSS feeds and generates pages and posts from them and tries to profit using say Adsense or affiliate ads. The pages are just excerpts and titles from RSS feeds (sometimes full posts), and while they do link back to your site (usually) – they’re not the type of links you want to get. These spam blogs don’t have any redeeming value at all, no contact information, and certainly no original content at all.

    Now – let’s take your blog, let’s say you have a birdwatching club in Buffalo, New York. You’ve developed a great site with loads of original content, bunches of articles, and your members visit regularly. The two things that you and other members talk about regularly are binoculars and digital cameras. This is what you could do…

    Craigslist is America’s garage sale. If you don’t live in America, I’m sure something like this is in your region. Craigslist offers RSS feeds on each and every page. Here’s how the birdwatching club could benefit from that.

    First – create a page template. From your WordPress theme directory, download “single.php” (or the theme template that creates post pages) to your desktop. Open it in Notepad or any text editor, and add the following lines of code to the top:

    /* Template Name: Craigslist Template */ ?>

    This is the tricky part, because each and every theme is different. You need to look for the following block of code (which is what prints the page content out):

    <div class="entry">
    <?php the_content(__('Read more &raquo;')); ?>
    </div>

    Right after those lines (or “the loop” in your template, you want to copy and paste this code:

    <?php include_once(ABSPATH . WPINC . '/rss.php');
    wp_rss('http://example.com/rss/feed/goes/here', 5); ?>

    That code comes from this page in the WordPress Codex. WordPress has a built in “RSS Parser” that will read any RSS feed and spit out a list of links is list ordered fashion to a page. So, if you visit the Buffalo Craigslist Photo page, you’ll find at the bottom of the page a little orange RSS icon. Click on that link, and then copy the URL, and paste it over the example URL in your template. The number (20) that comes after the URL is the number of items from the RSS feed to parse and display. Save the template, and upload it back to your theme directory of your WordPress blog.

    In your WordPress Dashboard, go to “Write -> Page”. Type some original content in the box, and scroll down to the bottom (in WordPress 2.5, on the sidebar in <2.5) and select “Craigslist Template”. Title your page “Craigslist”, and then save and publish the page. Now if you go to www.yourblog.com/craigslist you should see a listing of things from craiglist with your original content on top.

    Look what you did, now the Buffalo Birdwatchers Club won’t can look at photo equipment right on the member web site without having to go to Craigslist unless they see an item they like. You can add multiple feeds to the same page, just copy and paste that code block in multiple times with different RSS feed URL’s. Just remember, the more your add, the longer they take to parse, and the longer the page will take to load. I loaded 6 feeds @ 20 items per feed, and the page took about 20 seconds or so to load.

    This Craigslist example is just that – an example. If you want to see how this looks in realtime, look at this Craiglist RSS example I just built. You could use RSS feeds from just about anything, digg, google news – any site that has a feed. As long as you’re only using headline feeds and not stealing content – nobody should ever think you’re plagiarising them in any way, you’re sending them traffic. In your template file, before you parse the feeds add a few paragraphs of original content about what they user might find (on Craigslist – or whatever) and now you have a page with ever changing (daily) content, AND orignal content that google can index!

    Now, how do you monetize this? Well, use your noggin and add some affiliate banners, adsense, or other items above, below, or in your sidebar. There is a better way to monetize without using these though…

    eBay has RSS feeds – don’t they?  All you have to do is add your affiliate code to an eBay RSS feed, and you could use it instead of the Craigslist feed for a list of eBay items, and every time someone clicks, bids, and buys an auction you profit! First you have to be a member of the eBay Partner Network (EPN). Once logged in go to “Tools->Widgets->RSS Feed Generator”. Then just enter in what you’re looking for. Like Craigslist, you can “geo-target” what you want by scrolling down and checking “Items within 50 miles of xxxxx zip code”. Then click “search” and the page you get should be auctions for only that area. Again, scroll to the bottom of the page and see the orange RSS icon. Click on it and copy the URL and use that as the URL in the code block in your template, save the page now your blog page will list eBay auctions! The difference between these listings and Craigslist is that you profit from each won auction click on these.

    I’ve just given you a few ideas, the sky’s the limit with these. You could probably do the exact same thing with Amazon. Now, there’s one thing I didn’t tell you, often people want to know how to take an RSS feed an automatically create blog posts from the feed and publish them, kind of like what’s called an “auto-blog”. Let me state first that there are very few legit reasons to do this, because of duplicate content issues in google, etc. Most people want to use this to try and create quick spammy blogs with no original content, but there are (just a very few) legit reasons to want to create posts from an RSS feed (like doing a blogroll type page for members of a larger community). You can do that easily (and freely) with RadGeek’s Feed WordPress Plugin.

    Now, get hacking, come back to comment and tell me what you’ve come up with!

  • Leave a Comment
  • Learn How to Secure Your WordPress Blog

    We hear almost every day about bloggers getting their login information comprimised. Are you one of the many people that are growing increasingly concerned about their blogs security?

    If you are looking up ways to beef up the security of your WordPress blog, Make Tech Easier has posted a great article about 11 ways to secure your WordPress blog. The post includes a few security tips we’ve already covered in past posts, plus a bunch of other great tips.

    Here is what information the post covers:

    • Encrypt your Login
    • Stop Brute Force Attack
    • Use a Strong Password
    • Protect your WP-Admin Folder
    • Remove WordPress Version Information
    • Hide your Plugins Folder
    • Change your Login Name
    • Upgrade to the Latest Version of WordPress and Plugins
    • Do a Regular Security Scan
    • Backup your WordPress Database
    • Define user Privilege

    Click over to get descriptions, plugin information and more!

    Got any tips to add? Let us know in the comments below!

  • Leave a Comment
  • 6 WordPress Tips and Tricks

    Adding A Side Blog

    1. Pick a desired category and add it in your blog (i.e. category “Side Blog”)
    2. Implement the following code into your “Functions.php” in your theme’s directory:

    <?php
    function asidesFilter($query) {
    if($query->is_feed || $query->is_home || $query->is_ search) {
    $query->set(’cat’, ‘-115?);
    }return $query;}
    >add_filter(’pre_get_posts’, ‘asidesFilter’);>
    ?>

    (Notice the number 115 is the category ID number for the chosen category. Yours will be different.)

    3. Then add the following into your “sidebar.php” file in your theme’s directory:
    <h3>Side Blog
    <a href=”FEED URL” title=”My Side blog's RSS feed.”>
    <img src=”RSS IMAGE URL” alt=”RSS” style=”position: relative; left: 0;” />
    </a>
    </h3>
    <?php query_posts(’cat=115&showposts=2?); ?>
    <?php if(have_posts()) : ?>
    <?php while(have_posts()) : the_post(); ?>
    <div class=”aside_post”>
    <?php the_content(’Continue reading...’); ?>
    </div>
    <?php endwhile; ?>
    <span class=”aside_archive_link”>
    <a href=”CATEGORY URL” title=”More asides.”>Archives</a>
    </span>
    <?php else : ?><p>Sorry, the side blog is having a little trouble.</p>
    <?php endif; //if you delete this the sky will fall on your head ?>

    Enhancing Your “Read More” Link

    1. Open your “index.php” or file and find this line:
      <?php the_content(__(’Read more’));?>
    2. replace it with this one:
      <?php the_content(”Continue reading ” . the_title(”,”,false), 0); ?>

    Enhancing Your “Comments” Link

    1. Open your index.php, archive.php, and single.php and find this line:
      <?php comments_popup_link(’Leave a Comment’, ‘1 Comment’, ‘% Comments’); ?>
    2. Replace it with this one:
      <?php comments_popup_link(__(’No comments on ‘ . the_title(”,”,false)),
      __(’One comment on ‘ . the_title(”,”,false)), __(’% comments on ‘. the_title(”,”,false))); ?>

    Random Tip #1

    Do NOT use the following search code in the
    “search.php” file in your theme’s directory :
    <?php echo $_SERVER [’PHP_SELF’]; ?>
    Nobody should be allowed to search your entire server right?

    Use this instead:

    <?php bloginfo (’home’); ?>

    Random Tip #2

    Yet another bad code used in title tags or search templates:
    <?php echo $s; ?>
    as it allows some harmful Sql injections =(.

    Use this instead:
    <?php echo wp_specialchars($s, 1); ?>

    Random Tip #3

    Block search robots from your archive page by preventing the indexing:
    <?php if(is_archive()) { ?><meta name=”robots” content=”noindex”><?php } ?>
    Paste it anywhere in the “Header.php” file of your current theme’s directory in the <head> tags.

    Hope this helps. Thanks for reading and have a wonderful day!

  • Leave a Comment
  • Top 5 WordPress Navigation Menu Tutorials

    Navigation menu is a really important part of a website, both visually and functionally. Though, I noticed that most blogs use a really simple navigation menu. A simple menu can be good sometimes, but if you’re looking for something more sophisticated, I’m pretty sure you’re going to enjoy this list.

    Here’s 5 really cool tutorials to help you create a stunning navigation for your WordPress blog.

    Creating Two-Tiered Conditional Navigation in WordPress


    Which WordPress user doesn’t know Darren Hoyt, the creator the free magazine theme Mimbo Magazine ? In this great tutorial, Darren explains how to create a professional two-tiered navigation menu. Source

    How To: Making a Categories Drop-Down Menu


    This was my first post on Hack WordPress, and seems like you guys enjoyed it. In this tutorial, I explain how to create a navigation bar with a category drop-drown menu. Source

    WordPress: “Magazine style” Horizontal dropdown menu


    One of my last tutorials, published on my blog CatsWhoCode. This how-to explain how you can create an horizontal dropdown menu. Source

    Using Sliding Doors with WordPress Navigation

    This sliding doors CSS hack allows you to create sophisticated tabs for your navigation bar. Sadly, WordPress core functions wp_list_pages() and wp_list_categories() don’t allow you to add the required span tag to use this technique.
    This tutorial will show you how to bypass this limitation by using a hack, and then you’ll be ready to enjoy sliding-doors for your WordPress navigation! Source

    Any other navigation tutorial that should be in the list? Leave us a comment below!

  • Leave a Comment
  • How To: Insert Ads Only After the First Post

    Have you ever tried to insert advertisements (or any bit of code really) into the WordPress post loop, then found that it will insert the banner after each post?   It really depends on what you are going for, but this usually will not be an ideal solution to placing advertisements between posts on your homepage.   If you’d like to place something only after the first post in the WordPress post loop, here is a quick hack you can do to tell WordPress to only display it after the first post.

    Simply go to your themes homepage and look for the following code:

    <?php endwhile; ?>

    Immediately before this code, place the following code:

    <?php if(!$show_ads){ ?>
    Insert Code Here
    <?php $show_ads = 1; } ?>

    Obviously you’ll want to replace Insert Code Here with your code.  Told you it was easy!

  • Leave a Comment
  • How To: Adding a Store to Your WordPress Blog

    Depending on the type of WordPress blog you run, you may have an interest in building a small store into your blog.   I’ve found this is a great way to make some extra income to cover your blog costs while at the same time providing your readers with a useful resource.

    How to Add a Store To Your WordPress Blog

    The method I’m going to cover here is the method I use and have found a lot of success with.  It involves using a purchased software and eBay’s affiliate program to generate income.   Before I get started, I wanted to make one quick point.   This method is not for all blogs.  Because the generated income comes from being an eBay affiliate, this method is best applied to blogs that cover products or services that are regularly purchased on eBay.    Examples would be photography blogs (cameras and equipment), video game blogs (games and equipment), etc.   Things like celebrity blogs, make money online/affiliate marketing blogs, or personal blogs probably won’t find a lot of success with this method because it doesn’t relate well to an eBay product.

    In order to get started, you’ll first need to purchase the Build a Niche Store software (commonly referred to as BANS).  It has a one-time cost associated with it, but once you own the software, you get lifetime updates and you can use the software on unlimited sites.   The team behind BANS is incredible with both their dedication to updating the product as well as their support on their forums.   Owning BANS has really been a great experience for me.  The software has also developed a lot of trust over the past 2 years from its users, so it is a very safe investment.

    Once you’ve got your BANS license and downloaded the software, you’ll also get instructions on getting your first site setup.  It installs via a script so everything is really easy.  The only thing you’ll need to know how to do when purchasing this software is how to manually create a MySQL database (if you installed your WordPress software manually, you should already know how to do this).   You can always contact your web host to find out how to do this as well.

    You’ll want to create either a sub-domain or directory on your site where you want to place your new eBay store.   I generally use directories, but either should work the same.   Inside your new folder you created you’ll want to upload the BANS software and then visit the domain and go through the install.   If you run into any troubles on your first try, you can always consult the installation guide that comes with the product.

    How Do I Integrate Build a Niche Store (BANS) with WordPress?

    Now, BANS was not specifically created for use with WordPress, but was instead designed to run solo on a new domain name.   Fortunately, thanks to the hard working team over at The Niche Store Builder, you can now get WordPress themes that were specifically designed to integrate WordPress and BANS together.   In addition to creating their own unique BANS themes for WordPress, with Niche Store Builder you can also get BANS templates that were designed specifically for popular existing WordPress themes such as ThemeSpinner’s Chimera theme and Daily Blog Tips StudioPress theme.   You’ll get a matching skin for your BANS directory/subdomain and also a widget to display on the main site promoting some of your niche stores items.  These templates can be activated from the BANS control panel just like how a WordPress theme is activated.

    Here is a screenshot of BANS being used with the Chimera theme:

    And here is one for the popular StudioPress theme:

    I’ve been using this method on a few of my sites offering up cookbooks or whatever else is related to the content of the site and the income definitely helps cover domain renewals, hosting expenses, or whatever other costs come up.

    If you have any questions or run into any troubles, please let me know in the comments below!

  • Leave a Comment
  • How To: Add Social Bookmark Links to your Theme

    An essential step in your blog promotion is to have people voting for you on sites such as digg.com or StumbleUpon. So, why not make it easier to visitors to vote for your articles on social bookmarking sites? In this tutorial, I’ll show you how to create a fancy multi-widget to tell your readers to go vote for your posts.

    The problem

    Many visitors will not vote for you posts on digg or stumbleupon simply because they read and enjoyed it. They simply don’t think about it, exepted if they come from one of theses websites.

    Most social bookmarking sites provides widgets to add to your blog to provide your visitors an easy way to vote for your post. This is functionally good, but what about create something more personal, which will perfectly fit your blog theme colors?

    Creating the widget

    Let’s create our very own multi-widget. First of it all, download the sample image I created for you. It will serve as the background image in this example, but of course you can change it, or put a background color instead by using css.

    On my blog, I chose to display the multi-widget at the bottom of each post. Like this, the reader will only see it if he finished the article, and will probably vote for it if he liked.

    Open the single.php file from your blog theme, and paste the following code after your post:

    <div id="cwc-vote">
    <ul>
    <li><a href="http://del.icio.us/post?url=<?php echo the_permalink(); ?>">Del.icio.us (<span id='<?php echo md5("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);?>'>0</span>)</a></li>
    <li><a href="http://digg.com/submit?url=<?php echo the_permalink(); ?>">Digg</a></li>
    <li><a href="http://www.stumbleupon.com/submit?url=<?php echo the_permalink(); ?>">StumbleUpon</a></li>
    <li><a href="http://reddit.com/submit?url=<?php echo the_permalink(); ?>">Reddit</a></li>
    <li><a href="http://www.dzone.com/links/add.html?url=<?php echo the_permalink(); ?>">Dzone</a></li>
    </ul>
    </div>

    We now got a list with links to directly post (or vote if already posted) articles to the following sites: Del.icio.us, Digg, StumbleUpon, Reddit and Dzone.

    You can easily add others social bookmarking sites: I can’t guarantee that it will work for all sites, but basically, the link must look like this:

    <a href="http://www.yoursite.com/links/submit?url=<?php echo the_permalink(); ?>">

    CSS Styling

    For now, our multi-widget is fully functional, but a bit ugly. Happily, pasting the following CSS code to your style.css file will make the widget looks good.

    #cwc-vote{
        /* Don't forget to change the image path */
        background: #fff url(images/cwc-vote.png) no-repeat top left;
        width:600px;
        height:45px;
        padding-top:35px;
    }
    
    #cwc-vote ul{
        list-style-type:none;
        margin-left:-20px;
    }
    
    #cwc-vote ul li{
        display:inline;
        margin-right:-10px;
    }
    
    #cwc-vote ul li a{
        color:#fff;
        font-size:13px;
    }

    Adding live Del.icio.us count

    You probably noticed the (0) next to the Del.icio.us link. We’ll use the Del.icio.us api so we can get how much times the post has been bookmarked by users.

    Paste the following code in your single.php file, below the multi-widget.

    <script type='text/javascript'>
    function displayURL(data) {
    var urlinfo = data[0];
    if (!urlinfo.total_posts) return;
    document.getElementById("<?php echo md5("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);?>").innerHTML = urlinfo.total_posts;
    }
    </script>
    
    <script src='http://badges.del.icio.us/feeds/json/url/data?url=<?php the_permalink() ?>&callback=displayURL'></script>


    It is also possible to get the number of digg, but it’s a little harder, especially for beginners. Anyways, if you’re interested about it, tell me and I should make another tutorial.

    Now, you have a working multi widget to nicely tell your readers to vote for your article. On a personal note, I just made my first ever digg front page during the time I was writing this post and I think this multi-widget helped a lot. I wish the same to all of you :)

  • Leave a Comment
  • How To: Changing the Default WordPress Gravatar

    If you’ve been with WordPress awhile, you’ll probably remember back in October of 2007 when Automattic purchased Gravatar.   The concept behind Gravatar had always been an incredible idea, but it had always lacked the time and resources needed to make it work.  Now that Automattic acquired Gravatar, it was pretty obvious that the service would be resurrected and would be a great fit for the WordPress platform.

    Earlier this year when WordPress 2.5 came out, a shift was made in the WordPress community from the widely popular MyAvatars plugin (which uses MyBlogLog avatars) to Gravatars.   In addition to being built into WordPress.com blogs, we were also given the ability to build Gravatars into your WordPress.org blog.  But, did you know that WordPress.org blog owners can now also create your own custom default Gravatar image?

    Over at Pro Blog Design, Michael has written a great tutorial explaining exactly how to add your own default Gravatar image, as well as provide some tips on how to make a good Gravatar default image.

    In order to add the image you’ve made, you just need to take your Gravatar code and add the image URL right after the comma:

    Before

    <?php if(function_exists(’get_avatar’)){ echo get_avatar($comment, 50 );} ?>

    After

    <?php if(function_exists(’get_avatar’)){ echo get_avatar($comment, 50, 'http://www.wphacks.com/wp-content/themes/HackWordPressPro/images/nophoto.gif');} ?>

    Great tip Michael!  You’ll want to click over to see Michael’s tips on creating a custom “No Gravatar” logo for your website.

  • Leave a Comment
  • How to: Create an Archive Page for your WordPress blog

    In my opinion, all blogs should have an archive page: It allows your readers to quickly browse your blog and find what they’re looking for, and this page is also very good for SEO.

    Here’s how to create this page on a WordPress blog:

    Archive WordPress Plugins

    There’s many plugins which allows you to automatically create an archive page. The good thing is that you’ll have (almost) nothing to do, and the bad thing is that you will not be able to customize it a lot, or you’ll have to edit the plugin files, which is sometimes a bit too hard if you’re not a developer.

    On my blog in French, I use the Smart Archives plugin. Even if it gives me satisfaction, the loading time of the page is very long due to the amount of posts to be displayed simultaneously.

    If you want to use a plugin, you shall also give a try to Clean Archives, or Extended Live Archives, which allows numerous personalizations.

    Do it yourself

    WordPress allows you to create page templates, so it’s possible to create manually an archive page. This is what I chose to do on my blog in English, CatsWhoCode.com.

    Before starting to code, you’ll have to choose between two different kinds of archive page. The first one will list all your posts, and will allow a direct access to every article you wrote. The only bad thing is that when your blog will have many posts, the list may be a bit too long.

    The second template, which is better for blogs that have been online since more than one year, will list your posts monthly and by categories.

    Your choice is made?  So let’s go coding!

    First we’ll have to create a new file and name it archives.php. At the beginning of the file, paste the following lines:

    <?php
    /*
    Template Name: Archive page
    */
    ?>

    This php comment define a name for our template, and will later allows us to select it on WordPress Dashboard, when we’ll create a new page.

    First template: Listing all posts

    <?php
    $posts_to_show = 100; //Max number of articles to display
    $debut = 0; //The first article to be displayed
    ?>
    <?php while(have_posts()) : the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <ul>
    <?php
    $myposts = get_posts('numberposts=$posts_to_show&offset=$debut');
    foreach($myposts as $post) :
    ?>
    <li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    
    <?php endforeach; ?>
    </ul>
    
    <?php endwhile; ?>

    Second template: Archives by months and categories

    <?php while(have_posts()) : the_post(); ?>
    <h2><?php the_title(); ?></h2>
    
    <h2>Categories</h2>
    <ul><?php wp_list_cats('sort_column=name&optioncount=1') ?></ul>
    
    <h2>Monthly Archives</h2>
    <ul><?php wp_get_archives('type=monthly&show_post_count=1') ?></ul>
    
    <?php endwhile; ?>

    After you chose one of the templates I shown you above and pasted it to your archives.php file, you just have to upload it on your wp-content/theme/yourtheme/ directory.

    Then, in WordPress dashboard, create a new page, name it “Archives” (or whatever you want) and select Archive page as page template.

    That’s all! You now have an archive page, which is good for both your reader and search engines crawlers.

  • Leave a Comment