简体   繁体   中英

WordPress - 'The Loop' to show all posts, instead posts the title of the home page

I just started with a wordpress tutorial series and one of the first things it does was make a simple "the loop", to print the title and description of all of the posts. When I did it though, it prints the name and description of the home page.

<?php 
if ( have_posts() ) 
 {
  while ( have_posts() ) 
    {
        the_post(); 
        the_title('<h2><a href="the_permalink();"','</a></h2>');   
        the_content(); 
        // Post Content here
        //
    } // end while
 } // end if
?>

I cannot figure out why it prints the home page information instead of post info.

To display wordpress posts on any page , you need to pass the arguments as the following in the WP_Query and then loop them via object.

// The Query
$the_query = new WP_Query( array( 'post_type' => 'post','posts_per_page' => -1 ) );

// 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();
} else {
    // no posts found
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM