wordpress post showing twice on custom page template

1.3k views Asked by At

not sure what is wrong in code? but this is showing posts with id 64 twice. The goal is to have a page that shows posts from a certain category, that part works, just posts are showing twice.

<?php /* Template Name: Special Template */ ?>
<?php get_header(); ?>
<?php
    $hide_title_text = rwmb_meta('itrans_hide_title_text');
?>
<div id="primary" class="content-area">
    <div id="content" class="site-content" role="main">

<?php
query_posts('cat=64');
while (have_posts()) : the_post();
the_content();
endwhile;
?>

        <?php /* The loop */ ?>
        <?php while  ( have_posts() ) : the_post(); ?>

            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <header class="entry-header">
                    <?php if ( has_post_thumbnail() && !          post_password_required() ) : ?>
                    <div class="entry-thumbnail">
                        <?php the_post_thumbnail(); ?>
                    </div>
                    <?php endif; ?>
                    <?php if($hide_title_text != 1) { ?>
                    <h1 class="entry-title"><?php the_title(); ?></h1>
                    <?php } ?>
                </header><!-- .entry-header -->

                <div class="entry-content">
                    <?php the_content(); ?>
                    <?php wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'itransform' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>' ) ); ?>
                </div><!-- .entry-content -->

                <footer class="entry-meta">
                    <?php edit_post_link( __( 'Edit', 'itransform' ), '<span class="edit-link">', '</span>' ); ?>
                </footer><!-- .entry-meta -->
            </article><!-- #post -->

            <?php comments_template(); ?>
        <?php endwhile; ?>

    </div><!-- #content -->
    <?php get_sidebar(); ?>
</div><!-- #primary -->
2

There are 2 answers

1
tschaible On

You have a small loop early on:

while (have_posts()) : the_post();
the_content();
endwhile;

And then later on you have the larger loop with all the formatting that starts with:

        <?php /* The loop */ ?>
        <?php while  ( have_posts() ) : the_post(); ?>
        ...
        <?php the_content(); ?>
        ...
        <?php endwhile; ?>

Which will result in two posts on the page.

0
Jenis Patel On

It's better to use get_posts() or new WP_Query() over query_posts() as query_posts() will modify the main query.

For more details check out here : https://codex.wordpress.org/Function_Reference/query_posts

You can use the below mentioned approach for your requirements :

<?php
$args = array('category' => 64 );

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
    // get your required stuff here
endforeach; 
wp_reset_postdata();
?>