views:

638

answers:

3

I am trying to modify a wordpress / MySQL function to display a little more information. I'm currently running the following query that selects the post, joins the 'postmeta' and gets the info where the meta_key = _liked

    function most_liked_posts($numberOf, $before, $after, $show_count) {
 global $wpdb;

    $request = "SELECT ID, post_title, meta_value FROM $wpdb->posts, $wpdb->postmeta";
    $request .= " WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id";
    $request .= " AND post_status='publish' AND post_type='post' AND meta_key='_liked' ";
    $request .= " ORDER BY $wpdb->postmeta.meta_value+0 DESC LIMIT $numberOf";
    $posts = $wpdb->get_results($request);

    foreach ($posts as $post) {
     $post_title = stripslashes($post->post_title);
     $permalink = get_permalink($post->ID);
     $post_count = $post->meta_value;

     echo $before.'<a href="' . $permalink . '" title="' . $post_title.'" rel="nofollow">' . $post_title . '</a>';
  echo $show_count == '1' ? ' ('.$post_count.')' : '';
  echo $after;
    }
}

The important part being: $post_count = $post->meta_value;

But now I want to also grab a value that is attached to each post called wbphoto

How do I specify that $post_count = _liked and $photo = wbphoto

?

Here is a screen cap of my Phpmyadmin alt text

A: 

The SQL will look very ugly.

// Your Meta key names
    $metas = array(
        '_liked', '_another1'
    );

    foreach ($metas as $i=>$meta_key) {
        $meta_fields[] = 'm' . $i . '.meta_value as ' . $meta_key;
        $meta_joins[] = ' left join ' . $wpdb->postmeta . ' as m' . $i . ' on m' . $i . '.post_id=' . $wpdb->posts . '.ID and m' . $i . '.meta_key="' . $meta_key . '"';
    }
    $request = "SELECT ID, post_title, " .  join(',', $meta_fields) . " FROM $wpdb->posts ";
    $request .=  join(' ', $meta_joins);
    $request .= " AND post_status='publish' AND post_type='post'";
    $request .= " LIMIT $numberOf";

It will be better of making another SQL to retrieve meta themselves.

Darkerstar
Hmm thanks. How would I go about echoing out these values?
Wes
I think I've got it. This has worked great.
Wes
A: 

Hey Wes, how you solved this ? I'm stuck in the same right now.

eft0
The post below worked after some modification. I'll try post the code / email me [email protected]
Wes
A: 

Don't know if that could help you, but here's a working SQl query that get posts and post_meta.

SELECT DISTINCT ID, p.post_title, p.post_status, p.post_date, m.meta_key, m.meta_value 
FROM wp_posts p, wp_postmeta m
WHERE p.post_author = 2 
AND p.post_status = 'publish' 
AND p.post_date >= '2009-01-01' 
AND p.post_date <= '2010-05-28'
AND p.ID = m.post_id
Jean-Baptiste Jung