Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm new to wordpress. I'm having trouble with a query I wrote to fetch the previous and next posts. ( I check

$sql = "
SELECT * FROM wp_posts WHERE post_date < ( SELECT post_date FROM wp_posts WHERE ID = {$id} ) LIMIT 1
UNION
SELECT * FROM wp_posts WHERE post_date > ( SELECT post_date FROM wp_posts WHERE ID =  {$id} ) LIMIT 1
";

$wpdb->query($sql);

$arrPosts = $wpdb->last_result;

But I only get one post in $arrPosts. ( I know there are more than two). What's going on?

share|improve this question

1 Answer 1

Try:

$arrPosts = $wpdb->get_results($sql);

That said, note that there also is an API to get these two. See in particular:

get_next_post()
get_previous_post()
share|improve this answer
    
Oh, and mind the {$id} thingy. Be sure to cast it to int, if used as is. Or use $wpdb->prepare(). –  Denis Oct 23 '10 at 15:58
    
I do an is_numeric() beforehand. –  user1359 Oct 23 '10 at 16:58
    
get_next_post() and get_previous_post() didn't work for me -- I get NULL for both values. I'm using wp-load.php to get access to wordpress data. Is there something I'm missing? –  user1359 Oct 23 '10 at 17:00
    
Setting up post data, maybe? Either use the WP standard loop formula with if (have_posts()) : while (have_posts()) : the_post(); , or populate the $post variable with your post object and calling setup_postdata($post) before trying to use these functions. –  goldenapples Oct 23 '10 at 18:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.