Hatem Tito Hatem Tito - 1 month ago 9
PHP Question

how to loop through posts in both front page and blog page?

i want to display some posts in home page according to post type but i can't access posts and post loop returns " Home " post only ,so what is the proper way to make this happen ?

my reading settings


  • Front page displays : A static page

  • Front page :home

  • Posts page :blogs


Answer

Keep your reading settings the way they are.

You can create a theme file called front-page.php and use this to control your home page.

Within your front-page.php you can use get_posts to retrieve posts and then loop through them

Example:

<?php get_header(); ?>

<?php
$args = array(
    'numberposts' => 10, // number of posts to return
    'post_type' => 'your-post-type' // change this to the post type you want to retrieve
);


$posts = get_posts( $args );

if ( $posts ) : 
    foreach ( $posts as $post ) : setup_postdata( $post );  ?>

        <article <?php post_class(); ?>>
            <h1><?php the_title(); ?></h1>
            <?php the_content(); ?>
        </article>


    <?php endforeach; ?>
    <?php wp_reset_postdata(); ?>

<?php endif; ?>

<?php get_footer(); ?>
Comments