pjldesign
pjldesign

Reputation: 397

Exclude Featured Posts in Wordpress 'Recent Posts' Function

Can I use the "exclude" array in the wp_get_recent_posts function to exclude Featured Posts? I have a plugin called NS Featured Posts which pulls featured posts through a key in the wp query i.e.:

$custom_query = new WP_Query( 
    array(
        'post_type' => 'post', 
        'meta_key'   => '_is_ns_featured_post',
        'meta_value' => 'yes'
    ) 
);

could I somehow use this to target and exclude NS Featured Posts in the wp_get_recent_posts call e.g.:

$recent_posts = wp_get_recent_posts(array(
        'numberposts' => 3,
        'exclude' => (the ns featured posts)
    ));

Thanks for any insight.

Upvotes: 0

Views: 833

Answers (2)

Nathan Dawson
Nathan Dawson

Reputation: 19308

Functions such as wp_get_recent_posts() can accept all of the same arguments as WP_Query. While the documentation only lists a handful of parameters, the full set are available to you.

You had suggested using exclude in your query however that's going to want the IDs of the posts to exclude. You could of course grab those first but that's not going to be the most efficient solution.

The way to do this in a single query is with meta query options. The posts are being tagged with a meta key and a meta query will allow you to exclude those. You'll need to check both for the existence of the meta key and the value being 'yes'.

Example:

$recent_posts = wp_get_recent_posts( array(
    'numberposts' => 3,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => '_is_ns_featured_post',
            'value' => 'yes',
            'compare' => '!=',
        ),
        array(
            'key' => '_is_ns_featured_post',
            'compare' => 'NOT EXISTS',
        ),
    )
) );

Reference: https://codex.wordpress.org/Class_Reference/WP_Meta_Query

Upvotes: 1

user127091
user127091

Reputation: 2621

So I tested it now and getting posts without a certain meta key in one query is not possible.

But: You can exclude them from another query like so:

    $featured_posts = get_posts( [
        'meta_key' => '_is_ns_featured_post',
        'meta_value' => 'yes',
        'fields'     => 'ids',
    ] );

    query_posts( array( 'post__not_in' => $featured_posts ) );

    while ( have_posts() ) : the_post();
        $output .= '<li>'.get_the_title().'</li>';
    endwhile;

    wp_reset_query();

Upvotes: 1

Related Questions