Reputation: 175
I am trying to display results of a custom post type on my main wordpress page.
This is my code so far:
<?php
wp_reset_query();
$args=array(
'post_type' => 'rooms',
'post_status' => 'publish',
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<TABLE border="1" cellspacing="50">
<TR>FEATURED ACTIVE LISTINGS</tr>
<?php
while ($my_query->have_posts()) : $my_query->the_post();
$my_custom_fields = get_fields(get_the_ID());
if(isset($my_custom_fields['availability']) && $my_custom_fields['availability'] == 'Available'):
?>
<tr><td><?php echo the_post_thumbnail('thumbnail');?>
<br>UNIT <?php echo the_field('unit_number'); ?> <?php echo the_field('bedrooms'); ?>BEDS/<?php echo the_field('bathrooms'); ?>BA
<br>$<?php echo the_field('price'); ?></td>
</tr>
<?php
endif;
endwhile; ?>
</TABLE>
<?php }
wp_reset_query();
?>
This works. However, If I try to add 'posts_per_page' => 3,
into the array of args. It does not display any results at all. What am I doing wrong, or is there an alternative way to achieve this same result?
If it is relevant, The plugins I am using are Advanced Custom Fields and Custom Post Types.
Thanks in advance!
SOLVED:
I have actually figured it out myself, and thought I would share how I solved it.
'posts_per_page' => 3 was working but it would only show the last 3 posts of that type that was NOT being filtered by if(isset($my_custom_fields['availability']) && $my_custom_fields['availability'] == 'Available'):
In order to Limit posts that were being filtered by this field, I added my own counter and set it to be at max of 3. I changed the above line to if(isset($my_custom_fields['availability']) && $my_custom_fields['availability'] == 'Sold' && ($postcount < 3)): and added $postcount++; inside the loop.
Thanks again for your help. I hope this helps whoever else.
Upvotes: 3
Views: 14314
Reputation: 4221
In functions.php you should rather do the following:
// posts per page based on content type
function themename_custom_posts_per_page($query)
{
switch ( $query->query_vars['post_type'] )
{
case 'content_type_name': // Post Type named 'content_type_name'
$query->query_vars['posts_per_page'] = 3; //display all is -1
break;
}
return $query;
}
if( !is_admin() )
{
add_filter( 'pre_get_posts', 'themename_custom_posts_per_page' );
}
Source of this answer
Upvotes: 4
Reputation: 93286
The solution you found is only going to work under certain conditions. If there aren't three posts with availability set to "Available" out of the set you retrieve (probably the first ten), you're not going to have enough. You can do a custom query instead that specifies a custom field name and value, as described in the WP_Query documentation:
$args=array(
'post_type' => 'rooms',
'post_status' => 'publish',
'meta_key' => 'availability',
'meta_value' => 'Available',
'posts_per_page' => 3,
'ignore_sticky_posts'=> 1
);
$my_query = new WP_Query($args);
Upvotes: 5