Hi there,
I've been playing around with displaying a random post from a single category on a website and have, to my surprise, managed to cobble together code that gets things working right.
As I'm not very strong on PHP coding and mySQL query writing I thought I'd post up my code here to see if I've gone about things in a very roundabout way.
Please note this is working, so it's not a support query as such, but I'd love to hear feedback on my method anyway.
Problem:
Display a single random post from a specific category in the website sidebar where the single post displays:
- Post Title
- Thumbnail image as defined in custom meta field in each post in this category
- Link to the post
Solution:
<li class="widget"><h2><span>Recent</span> Clients</h2>
<?php
$querystr = "SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->term_taxonomy.term_id = 3 AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->postmeta.meta_key = 'client-logo'
ORDER BY RAND() LIMIT 1";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
<?php if ($pageposts): ?>
<ul>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
<li>
<h3><?php the_title(); ?></h3>
<?php $clientlogo = get_post_meta($post->ID, 'client-logo', true); if (!empty($clientlogo)) {echo '<img src="' . $clientlogo . '" width="138" alt="Client Logo" />
';}?>
<a href="<?php the_permalink() ?>" rel="bookmark">View profile</a>
</li>
<?php endforeach; ?>
</ul>
<?php else : ?>
<ul>
<li><h3>Sidebar Error</h3>
Error message
</li>
</ul>
<?php endif; ?>
</li>
I really wasn't expecting it to work straight off, but with code borrowed from the following Codex pages and support topics, it did.
- Displaying Posts Using a Custom Select Query
- Function Reference: wpdb_Class
- Modifying Matt's Random Post Plugin
I absolutely wanted to avoid modifying the core as suggested by Otto42 here:
http://wordpress.org/support/topic/125739?replies=10
Whilst it looks like it will work fine, I'm bound to mess it up with a future WP update. I'm looking forward to &order_by=RAND becoming a standard part of the query_posts function though. Hopefully we'll see this in 2.4.
If I've got this right, hopefully it will be of some assistance to someone else.
Cheers,
Alex