简体   繁体   中英

List blog titles on custom page

I have a static homepage on my wordpress blog. I wan't to list the latest post title in a selected area on all other pages. So I have this code.

<?php

        $args = array(
          'showposts' => '1'
        );
        $the_query = new WP_Query( $args );

        if ( $the_query->have_posts() ) {

        ?>

            <header>
                <h2 class="latestPost"><a href="#"><?php the_title(); ?></a></h2>
            </header>

        <?php

        } else {
            // no posts found
        }
        wp_reset_postdata();

        ?>

This doesn't display the latest post title as I wan't, It displays the title of the page the visitor is at.

What am I doing wrong?

Try like this

$args = array(
      'showposts' => '1'
    );

    $the_query = new WP_Query( $args );
    // The Loop
    if ( $the_query->have_posts() ) {
            $the_query->the_post(); ?>
            <header>
            <h2 class="latestPost"><a href="#"><?php the_title(); ?></a></h2>
            </header>
        <?php
    } else {
        // no posts found
    }
    /* Restore original Post Data */
    wp_reset_postdata();
<?php query_posts('showposts=1'); ?>
<?php if (have_posts()) : the_post(); ?>

 <header>
     <h2 class="latestPost"><a href="#"><?php the_title(); ?></a></h2>
 </header>
<?php

    } 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