Listing wordpress pages with descriptions
31 Oct 2009Whilst building this site I wanted to implement wordpress in a way which didn’t make the site stand out as mainly being a blog. This approach led me to set up a number of static pages and I wanted to have an index of these pages for the projects page which would automatically update as I added new projects. Currently wordpress provides a function to list the titles of all static pages, as links, using the wp_list_pages()
method, however I wanted each page to be listed with a description, a task for which wordpress doesn’t provide a function so to solve this I wrote my own script which queried the appropriate bits of the database and made the page I wanted:
First I created a new php page template which would act as the index page.
Then I wrote a SQL query which extracts all the pages which are set as children of the index page (this requires that all pages you wish to appear in the index are set as children of the page).
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'page' AND $wpdb->posts.post_parent = '68' ORDER BY $wpdb->posts.post_title ASC";
Then executed the query. Now the appropriate data has been retrieved all that remains is to loop through it and process it and add it to the page:
<h3><a title="Permanent Link to <?php the_title(); ?>" href="<?php the_permalink() ?>"></a></h3>
To add the description to each page I used a custom field when adding each page, in this case I called it “des”. Custom fields are stored as a multi dimensional array named $custom_fields in each post from which the appropriate field can be retrieved:
$my_custom_field = $custom_fields['des'];
<?php echo '<div id="des">'.$my_custom_field[0].'</div>';
Now the page can be completed by adding any footer or sidebar required and added to the site as normal as a new blank page using the page just created as a template.
The whole script can be downloaded here.