L. Leo
L. Leo

Reputation: 53

How to get all the post titles on a specific page in WordPress

I want to display all the posts on a specific page called "Articles".

However, when I used the_title(); in a loop, it seems that the title of this page is displayed instead.

relative code in articles.php (linked to the Articles page created in dashboard)

<div class="container">
    <?php if ( have_posts() ) : ?>
        <div class="content">
            <?php while ( have_posts() ) : the_post(); ?>                
                <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>                
                    <?php get_template_part( 'content', get_post_format() ); ?>                                            
                </div>                                                    
            <?php endwhile; ?>
        </div>
    <?php endif; ?>
</div>

content.php

<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post-header section medium-padding">   
    <div class="post-meta-top"> 
        <?php the_time(get_option('date_format')); ?>

        <?php 
            if ( comments_open() ) {
                echo '<span class="sep">/</span> '; 
                if ( is_single() )
                    comments_popup_link( '0 comments', '1 comment', '% comments', 'post-comments' ); 
                else
                    comments_number( '0 comments', '1 comment', '% comments' ); 
            }
        ?> 
    </div>

    <h2 class="post-title"><?php the_title(); ?></h2>           
</a>

This part works well in index.php.

Upvotes: 0

Views: 497

Answers (1)

Johann Kratzik
Johann Kratzik

Reputation: 794

Step 1: Create a new template articles.php inside the folder of content.php and insert this code:

<?php
$articles = new WP_Query( array( 'posts_per_page' => -1 ) );

while ( $articles->have_posts() ) :
$articles->the_post();
?>

<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post-header section medium-padding">   
<div class="post-meta-top"> 
    <?php the_time(get_option('date_format')); ?>

    <?php 
        if ( comments_open() ) {
            echo '<span class="sep">/</span> '; 
            if ( is_single() )
                comments_popup_link( '0 comments', '1 comment', '% comments', 'post-comments' ); 
            else
                comments_number( '0 comments', '1 comment', '% comments' ); 
        }
    ?> 
</div>

<h2 class="post-title"><?php the_title(); ?></h2>           
</a>
<?php endwhile; ?>

Step 2: In articles.php replace this line:

<?php get_template_part( 'content', get_post_format() ); ?>

with this one:

<?php get_template_part( 'articles' ); ?>

Not tested but it should work.

Upvotes: 1

Related Questions