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 currently have this query_posts that i have done, (I am new to PHP!) And would like to know how I would go about limiting it to latest 4 posts and 4 posts only..

<?php query_posts('post_type=page&post_parent=2&posts_per_page=-1&orderby=title&order=ASC'); ?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

<!-- Calender Items -->

<?php $key = 'next_open_day'; $themeta = get_post_meta($post->ID, $key, TRUE); if($themeta != '') { 

echo '<div class="mopenday">';
echo '<img src="';
the_field('university_main_image');
echo '" width="160" height="40" />';
echo '<br />';
echo '<h2 class="od">';
echo '<a href="';
the_permalink();
echo '">';
the_title();
echo '</a>';
echo '</h2>';
echo '<p class="mdate">';
the_field('next_open_day');
echo '</p>';
echo '<p>';
the_field('open_day_description');
echo '</p>';
echo '<a class="visitweb" target="_blank" href="http://';
the_field('university_web_address');
echo '">';
echo 'Visit Website';
echo '</a>';
echo '</div>';

} ?>    

<!-- END OF CALENDER ITEM -->   

<?php endwhile; ?>
<?php wp_reset_query(); ?>
<!-- END OF PHP OPEN DAYS -->
share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

You have posts_per_page = -1, which means show unlimited posts. Change the -1 to the number of posts you want to appear.

Also you have output that skips if your "next_open_day" meta value is null, but the query will only run 3 times, so you need to move that logic into the query itself by using these arguments in the query_posts().

<?php
$metakey = 'next_open_day';
$args = array('post_type' => 'page',
              'post_parent' => 2,
               'posts_per_page' => 3,
               'orderby' => 'title',
               'order' => 'ASC',
               'meta_query' => array( 
                   array('key' => $metakey,
                         'value' => '',
                         'compare' => '!='
                   )
               )
);

query_posts($args);
?>
share|improve this answer
    
when I change the -1, none appear at all. –  Owen O'Neill Sep 17 '12 at 11:26
    
Are you changing the -1 to a positive number such as 10? It should look something like this: <?php query_posts('post_type=page&post_parent=2&posts_per_page=10&orderby=title&order=‌​ASC'); ?> –  Dave Hunt Sep 17 '12 at 13:50
    
I changed it to 4 and it works, but 3 doesn't... any idea why? –  Owen O'Neill Sep 17 '12 at 13:50
    
I've updated the answer –  Dave Hunt Sep 18 '12 at 21:58
    
Thank you very much! –  Owen O'Neill Sep 23 '12 at 23:01
show 2 more comments

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.