-1

I want to use custom page template for posts. So I create new php file:

<?php /* Template Name: Blog-2-col */ ?>
<?php get_header(); ?>

<div class="content">

    <?php
    if ( have_posts() ) : ?>

        <div class="container">
            <div class="row">
                <?php while ( have_posts() ) : the_post();?>
                    <?php get_template_part( 'template-parts/blog-2-col', get_post_format() );?>
                <?php endwhile; ?>
            </div><!-- row -->
        </div><!-- ontainer -->

        <div class="container">
            <div class="row">
                <div class="col-sm-12">
                    <?php wpbeginner_numeric_posts_nav(); ?>
                </div>
            </div>
        </div>

    <?php else :?>
        <?php get_template_part( 'template-parts/content', 'none' );?>
    <?php endif; ?>

</div>

<?php get_footer();

But I can't get posts in loop.

0

Your code will only display a list of your posts if the page that is using that template is set to be the Posts Page (in admin settings).

If you want any other page to display a list of posts, then you need to write a custom query inside the template.

E.g. using WP_Query:

$args = array(
    'post_type'      => 'post',
    'posts_per_page' => -1
);

$query = new WP_Query($args);

<div class="content">

<?php
if ( $query->have_posts() ) : ?>

    <div class="container">
        <div class="row">
            <?php while ( $query->have_posts() ) : $query->the_post();?>
                <?php get_template_part( 'template-parts/blog-2-col', get_post_format() );?>
            <?php endwhile; ?>
        </div><!-- row -->
    </div><!-- ontainer -->

    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <?php wpbeginner_numeric_posts_nav(); ?>
            </div>
        </div>
    </div>

<?php else :?>
    <?php get_template_part( 'template-parts/content', 'none' );?>
<?php endif; ?>

Or, you could create a shortcode which would contain pretty much the same code as above. And then you could use that shortcode in the page's content. Then, in the template:

if(have_posts()){
    while(have_posts()){
      the_post();
      the_content();
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.