0

Trying to show featured posts on home using catID,but it is being duplicated. Is there any way to prevent it from duplicating:

<?php
 query_posts("posts_per_page=1&cat=1");
if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php the_post_thumbnail(); ?>
<p><?php the_excerpt(); ?></p>
<p><a href="<?php the_permalink(); ?>">continue reading</a></p>
<?php endwhile; ?> <?php wp_reset_query(); ?>

2 Answers 2

0

Try to use wp_query instead of query_posts

1
  • which part of templates is the best part for adding extra codes or editing as wishes content-page.php or content.php or index.php ?
    – Dragut
    Commented Feb 21, 2015 at 20:57
0

Before I start, you should never make use of query_posts unless your intention is to break almost everything on your page :-)

Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).

To accomplish this, you should use WP_Query, and the post__not_in parameter. You must first get an array of the all the post ID's on the page, and then use that to exclude those posts in your query

You can try something like this on your page

$post_ids = wp_pluck_list($wp_query->posts, 'ID'); 
$args = array(
    'posts_per_page' => 1,
    'cat'            => 1,
    'post__not_in'   => $post_ids
);
$q = new WP_Query($args);

if ($q->have_posts()) {
    while($q->have_posts()) {
    $q->the_post();

       //Your loop

    }
    wp_reset_postdata();
}
3
  • if we want to retrieve posts based on specific cats such as "Featured", should we do like this: 'category_name' => Featured or ?
    – Dragut
    Commented Feb 22, 2015 at 14:53
  • category_name should be the category slug, not the name. You can use that in place of cat Commented Feb 22, 2015 at 14:56
  • If you want to make use of the category name, you will need to use a tax_query, none of the category parameters accepts the category name Commented Feb 22, 2015 at 15:00

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.