0

I'm trying to add a box in index.php where to show the latest 3 featured posts. According to this tutorial, I've added the following to functions.php:

add_theme_support( 'featured-content', array(
    'filter'     => 'magdeleine_get_featured_posts',
    'max_posts'  => 3,
) );

function magdeleine_get_featured_posts() {
    return apply_filters( 'magdeleine_get_featured_posts', array() );
}

function magdeleine_has_featured_posts( $minimum = 1 ) {
    if ( is_paged() )
        return false;

    $minimum = absint( $minimum );
    $featured_posts = apply_filters( 'magdeleine_get_featured_posts', array() );

    if ( ! is_array( $featured_posts ) )
        return false;

    if ( $minimum > count( $featured_posts ) )
        return false;

    return true;
}

Then I've created a featured.php template like this:

<?php
// Get our Featured Content posts
$featured = magdeleine_get_featured_posts();

// If we have no posts, our work is done here
if ( empty( $featured ) )
    return;

foreach ( $featured as $post ) : setup_postdata( $post );
?>

    [...post code...]

<?php endforeach; ?>
<?php wp_reset_postdata(); ?>

Last, I've called the template inside index.php this way:

<!-- Editor's picks -->
<?php if ( magdeleine_has_featured_posts( 1 ) ) : ?>
    <?php get_template_part( 'featured' ); ?>
<?php endif; ?>                     

<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
...

But... How to avoid repeating the same posts in the loop?

1 Answer 1

0

A simple approach could be to use a global array in which you will store posts that are selected in the featured query. You could set this array in your functions.php or index.php : $featured_post_array = array(); Then in your featured.php file first call the global array somewhere in the beginning:

global $featured_post_array;

and inside the foreach loop add :

$featured_post_array[] = $post->ID;

Last in the index.php in your query arguments use the post__not_in parameter:

$query = new WP_Query( array( 'post_type' => 'post', 'post__not_in' => $featured_post_array ) );

Another way would be to ignore posts with the tag (or taxonomy) "featured" by using the tag__not_in or category__not_in parameters

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.