WordPress Query to fetch both posts and pages by a custom field/key

I am working on a slider where I will show some contents(featured image and excerpt) pulled from both posts and pages. I want to filter the posts/pages by a custom field called ‘slider’!

So if there are some pages and posts with ‘slider’ custom field only those will appear in the slider. Is it possible in wordpress? If it is then how?

Read More

Some guidance will be appreciated!

Related posts

Leave a Reply

1 comment

  1. What you’re looking for is the class called WP_Query, has got a detailed explanation in the Codex. Take a look at the post_type argument which accepts an array, thus you can give it a array( 'post', 'page' ) or any other post types that you want to fetch.

    Now the meta fetch could be done in two ways, either via the new meta_query argument (from 3.1 onwards I believe) or meta_key and meta_value which are deprecated since 3.1.

    Here’s a rough example (haven’t checked if this works):

    $sider_posts = new WP_Query( array(
        'post_type' => array( 'post', 'page' ),
        'meta_query' => array(
            array(
                'key' => 'slider',
                'value' => 'yes',
                'compare' => '='
            )
        )
    ) );
    
    while ( $slider_posts->have_posts() ) {
        $slider_posts->the_posts();
    
        // output the slide here
    }
    

    Hope that makes sense. Cheers!

    ~ K