[resolved] Code too complicated for random post displaying custom meta? (3 posts)

  1. alexleonard
    Posted 7 years ago #

    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.


    Display a single random post from a specific category in the website sidebar where the single post displays:

    1. Post Title
    2. Thumbnail image as defined in custom meta field in each post in this category
    3. Link to the post


    <li class="widget"><h2><span>Recent</span> Clients</h2>
    $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'
    $pageposts = $wpdb->get_results($querystr, OBJECT);
    <?php if ($pageposts): ?>
    <?php foreach ($pageposts as $post): ?>
    <?php setup_postdata($post); ?>
        <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>
    <?php endforeach; ?>
    <?php else : ?>
        <li><h3>Sidebar Error</h3>
        Error message
    <?php endif; ?>

    I really wasn't expecting it to work straight off, but with code borrowed from the following Codex pages and support topics, it did.

    I absolutely wanted to avoid modifying the core as suggested by Otto42 here:


    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.


  2. The next version of WordPress is 2.5, not 2.4.

    And I've had a ticket in on trac for a while now. I put in a new patch after reading your post, so hopefully it'll get added in there.


  3. alexleonard
    Posted 7 years ago #

    Deadly. Thanks Otto :)

    Looking forward to 2.5!

Topic Closed

This topic has been closed to new replies.

About this Topic