WordPress functions not available in template

I am editing front-page.php and there I use get_posts() to output posts.
The other ways like using the_post are not working. So I need to output excerpt, but $post->post_excerpt is empty and the_excerpt function does nothing. I don’t understand why, cause there are no errors. Here is the code:

<?php

    foreach ( get_posts() as $post ) { ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class('article-item well'); ?>>
            <h2 class="title text-primary">
                <a href="<?php echo $post->guid; ?>">
                    <?php echo $post->post_title; ?>
                </a>
            </h2>
            <p class="article-info text-center">
            <span class="date">Posted on <time pubdate="" title="12:19 pm" datetime="<?php echo $post->post_date; ?>" class="time">
                    <?php echo $post->post_date; ?>
                </time>
            </span>
            </p>
            <?php if (has_post_thumbnail()) { ?>
                <figure class="img-wrap">
                    <?php the_post_thumbnail('full'); ?>
                    <figcaption class="label label-primary">
                        <?php foreach((get_the_category()) as $category) {
                            echo $category->cat_name . ' ';
                        } ?>
                    </figcaption>
                </figure>
            <?php } ?>
            <p>
                <?php the_excerpt(); ?>
            </p> 

BTW the_ID function is working and outputs post’s id properly.

Related posts

Leave a Reply

1 comment

  1. On each iteration of the loop you need to ‘setup’ post data, you do this using setup_postdata( $post );

    Amend your code as follows:

    <?php
    
    foreach ( get_posts() as $post ) { 
        setup_postdata( $post );
        ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class('article-item well'); ?>>
            <h2 class="title text-primary">
                <a href="<?php echo $post->guid; ?>">
                    <?php echo $post->post_title; ?>
                </a>
            </h2>
            <p class="article-info text-center">
            <span class="date">Posted on <time pubdate="" title="12:19 pm" datetime="<?php echo $post->post_date; ?>" class="time">
                    <?php echo $post->post_date; ?>
                </time>
            </span>
            </p>
            <?php if (has_post_thumbnail()) { ?>
                <figure class="img-wrap">
                    <?php the_post_thumbnail('full'); ?>
                    <figcaption class="label label-primary">
                        <?php foreach((get_the_category()) as $category) {
                            echo $category->cat_name . ' ';
                        } ?>
                    </figcaption>
                </figure>
            <?php } ?>
            <p>
                <?php the_excerpt(); ?>
            </p>