Sikander
Sikander

Reputation: 2835

WordPress : using page template to fetch posts in wp page

i want to display posts in wp page. to do that this is what i did i created a template named mypage-page.php and copied code from page.php to mypage-page.php

this is my mypage-page.php

          <main id="main" class="site-main" role="main">
                   <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

                            <h2><?php the_title() ;?></h2>
                            <?php the_post_thumbnail(); ?>
                            <?php the_excerpt(); ?>

                    <?php endwhile; else: ?>

                            <p>Sorry, no posts to list</p>

                    <?php endif; ?>

        </main><!-- .site-main -->
       //   this has header and footer as well . 

now i created a page mytest using this template ,what i expect it should list posts but it does not, please help me to understand where i'm wrong . i'm just a beginner

Upvotes: 0

Views: 249

Answers (2)

nim
nim

Reputation: 507

you can also use this, query_posts

Upvotes: 0

mmaumio
mmaumio

Reputation: 127

If your page is a Custom Page template then you have initialise a custom query. WordPress's default query won't work in a custom page template.

You can do that query using WP_Query Class : https://codex.wordpress.org/Class_Reference/WP_Query

Or get_posts() : https://codex.wordpress.org/Template_Tags/get_posts

I'd suggest the earlier one.

Upvotes: 2

Related Questions