Custom Post Type loop posts_per_page not working
-
I need help with getting a loop for a CPT working.
Here’s the problem: If I use a “foreach” statement instead of a “if/while” statement, it returns results but the post_per_page does not work (same with using numberposts) – I get a few results, but not the number I’m calling for. If I use posts_per_page=-1 I get all results, but I want to use it in a sidebar and limit it to 5 posts. I get either 2 or 3 posts returned when there are 8 total it *could* return, leaving me scratching my head.
If I use “if/while”, I get no results. No error, just no results.
I’m trying to show future scheduled events for a custom post type setup for “Hikes”. I’m using a custom field for the future date (‘hike_date_start’), and converting that date to a timestamp using strtotime, then comparing it to the current date to show only those that are greater-than or equal to current date. It works great on the Page for all the hikes when I use posts_per_page=-1. All future scheduled posts display correctly.
However, when I take that SAME query/loop and put it in a widget (PHP Code widget) to show it in the sidebar, the ONLY modification is that I change posts_per_page=-1 to posts_per_page=5. I also (because I’m using it as a secondary loop in the sidebar) add wp_reset_query to the beginning and end.
Here’s my sidebar code:
wp_reset_query(); global $post; $myposts = query_posts('post_type=hike&meta_key=hike_date_start&orderby=meta_value_num&order=ASC&posts_per_page=5'); foreach ( $myposts as $post ) : $exp_date = strtotime(get_post_meta($post->ID,'hike_date_start',true)); $today = time(); if ($today <= $exp_date) { ?> ...(do stuff)... } endforeach; wp_reset_query();
And yet even though the only difference is that I want to restrict the result to just the 5 posts, it only returns 3. I could understand if I got none, or 8 (the number of actual posts), but why 3? Why does it work perfectly on a Page, but not in a sidebar?
- The topic ‘Custom Post Type loop posts_per_page not working’ is closed to new replies.