nemrod.se Various guides and experiments

Custom page listing with thumbnails for WordPress [PHP]


I have run into several cases where I need to list subpages to a certain page in a neat little list with thumbnails, mostly for listing products. Since I’ve had to reuse it several times I thought I might as well share it since others might be looking for something similar. To see it in action here are two examples (both in Swedish, but you get the idea from the visuals): Bröllopsklänningar and Begagnade båtar. As you can see they list them differently, the first lists them in a grid while the second lists them in a list with excerpts attached. The code below is the first, but it’s easily customisable, tell me if you want any help!

<?php
    $children = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = $post->ID AND post_type = 'page' AND post_status = 'publish' ORDER BY menu_order", 'OBJECT');
    if($children) {
        echo '<table><tr>';
        $j = 0;
        foreach($children as $child) {
            setup_postdata($child);
            $attachment = get_posts("post_type=attachment&orderby=menu_order&order=ASC&post_parent=$child->ID");
            if($attachment) {
                $i = 0;
                for($i = 0; $i < sizeof($attachment); $i++) {
                    if('application/pdf' != $attachment[$i]->post_mime_type) {
                        $image = wp_get_attachment_thumb_url($attachment[$i]->ID);
                        break;
                    }   
                }   
            }   
            if($j && $j % 4 == 0) {
                echo '</tr><tr>';
            }   
            echo '<td>';
            echo '<h2><a href="' . get_permalink($child->ID) . '">' . $child->post_title . '</a></h2>';
            if($image) {
                echo '<a href="' . get_permalink($child->ID) . '"><img src="' . $image . '" /></a>';
            }   
            echo '</td>';
            unset($image);
            $j++;
        }   
        echo '</tr></table>';
    }   
?>

There are some minor improvements that can be made to pretty up the code – the $j variable for example I’d rather have in a for-loop and replace the foreach, but it was an addition to the code where the variable wasn’t needed at all and I haven’t been buggered to make any such changes. ;)


Posted in WordPress | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *