0

I have a function that lets me display the latest posts on my website, however i want to function to show posts of multiple categories at not just one specific category. Check the code below and what i'm saying may start to make sense.

function latestposts()   {
    $args = array( 'posts_per_page' => 4, 'cat' => '4', '5', '6', '7');                  
    $last_5_posts_query = new WP_Query( $args );
    while($last_5_posts_query->have_posts()) : 
        $last_5_posts_query->the_post();
        $link = get_permalink();
        $title = get_the_title();                           

        $content .= '<div class="thepost">';
        $content .= '<div class="thumbnail">' 
        . get_the_post_thumbnail( null, "home-post-thumbnail") 
        . '</div>';
        $content .= '<h3><a href='.$link.' target="_top">'.$title.'</a></h3>';
        $content .= '<p class="excerpt">' .get_the_excerpt(). '</p>';
        $content .= '</div>';
    endwhile;

return $content;

I made an attempt of making it show multiple categories with the below code, however it only shows items populating category 4. How do i make it display the posts from multiple categories? I thought the code below would work, but alas, does not.

$args = array( 'posts_per_page' => 4, 'cat' => '4', '5', '6', '7'); 

1 Answer 1

1

This is incorrect formatting of a PHP array:

'cat' => '4', '5', '6', '7'

Use category__in and pass an array of category IDs:

$args = array(
    'posts_per_page' => 4,
    'category__in' => array( 4, 5, 6, 7 )
);

See WP_Query for all valid parameters and how to format them correctly.

2
  • Using the code you posted, it brings back an error. Parse error: syntax error, unexpected T_DOUBLE_ARROW Commented Apr 4, 2013 at 16:28
  • You've not inserted it correctly within your code, likely left out array somewhere, impossible to tell you how to fix it without seeing it.
    – Milo
    Commented Apr 4, 2013 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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