1

This code only returns the name of a custom page I built -home. Why is it returning the page title? I want to display posts.

 <?php
     if ( have_posts() ) {
     while ( have_posts() ) {

    the_post(); ?>

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

    <?php the_content(); ?>

<?php }
 }
 ?>
4

Explanation in the comments:

<?php
/* This is your original loop (`have_posts`). Even on a custom template, the first loop references
the PAGE to which your template is-- this being your homepage. In order to display posts,
you must use a new query, as in the next chunk of code. */

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <?php the_content(); ?>

<?php
    }
}
?>

Here is how to get posts:

/* You can replace your original loop with the code below. This will query 10 posts
and return their titles.
See http://codex.wordpress.org/Class_Reference/WP_Query for customizing it. */

$args = array(
    'post_type'         => 'post',
    'posts_per_page'    => 10
);
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
}
/* Restore original Post Data */
wp_reset_postdata();

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.