1

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?

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()
4
  • Oh, and mind the {$id} thingy. Be sure to cast it to int, if used as is. Or use $wpdb->prepare(). 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. Oct 23 '10 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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