0

Im trying to create a wordpress loop which pulls out 4 specific pages/posts by ID (excepts to display a teaser). The main issue is they are located in 3 different post types: 'post', 'training', 'page'.

So far I have rewrote this code 3 times, its nearly there but not quite right.

<?php
$ids = array(2101,3754,4760,2572);
query_posts(array(
'post_type' => array( 'post', 'training', 'page' ),
'post__in' => $ids,
'posts_per_page' => 1) 
);

if (have_posts()) : 
?>

Can anyone give me a pointer into what is going wrong?

  • 1
    I strongly recommend against using query_posts, you should use WP_Query or pre_get_posts instead – Tom J Nowell Mar 11 '14 at 11:13
0

Never under any circumstances use query_posts. There is no excuse.

Use WP_Query instead. According to the WP_Query documentation, post_type accepts a value of 'any'.

$ids = array(2101,3754,4760,2572);
$query = new WP_Query(array(
    'post_type' => 'any',
    'post__in' => $ids,
    'posts_per_page' => 4
));

if ( $query->have_posts()) {
    while( $query->have_posts() ) {
        $query->the_post();
        the_title(); // etc
    }
    wp_reset_postdata(); // cleanup after our query
}

You also set it to return 1 post per page, but since you're not dealing with pagination, you want 4 posts, not 1, so increase that to 4

I would also advise against hardcoding your post IDs. A category name may be a better choice, or a 'featured items' taxonomy thats shared across both pages and posts, or better yet, a post meta value, with a metabox with a checkbox in it. All of which are subjects for other questions

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.