Shibbir
Shibbir

Reputation: 2031

WordPress get_posts() is NOT returning template tags

I want to get the latest 5 posts using WordPress get_posts function. I did the following:

In functions.php file I have added extra.php file which contain following code:

if( !function_exists( 'evertstrap_post' ) ) {
function evertstrap_post() {

        $args  = array(
            'post_type' => 'post',
            'numberposts' => 5,
        );

        $recent_posts = get_posts( $args );

        foreach ( $recent_posts as $post ) {
            setup_postdata( $post );
            echo get_the_title();
            echo '<br/>';
        }
        wp_reset_postdata();

    }
}

Now, from home.php file I am calling evertstrap_post() BUT it's not get the latest 5 posts !!

BUT

If I directly put the code into index.php file then it's working.

How can I solve it?

Upvotes: 1

Views: 160

Answers (2)

Paweł Witek
Paweł Witek

Reputation: 181

Try this:

if( !function_exists( 'evertstrap_post' ) ) {
    function evertstrap_post() {

            $args  = array(
                'post_type' => 'post',
                'numberposts' => 5,
            );

            $recent_posts = get_posts( $args );

            foreach ( $recent_posts as $post ) {
                setup_postdata( $post );
                echo get_the_title($post->ID);
                echo '<br/>';
            }
            wp_reset_postdata();

        }
    }
  1. You saw only last post title 5 times because get_the_title() is a template tag used in "while post : do post" wordpress loop. However the same function accepts argument with post ID. more here: https://developer.wordpress.org/reference/functions/get_the_title/
  2. Getting posts via function get_posts() you store post obejcts in an array and using normal foreach loop you can retrieve object data using $post->key_name within this loop. PHP: Getting data out of an object
  3. Also I recommend wordpress codex. Its very well documented.

Upvotes: 0

sundaycode
sundaycode

Reputation: 468

I've seen this sometimes in WordPress where echoing the output is unfavorable. Could you give this a shot?

if( !function_exists( 'evertstrap_post' ) ) {
function evertstrap_post() {
        global $post;

        $args  = array(
            'post_type' => 'post',
            'numberposts' => 5,
        );

        $recent_posts = get_posts( $args );

        $output = '';

        foreach ( $recent_posts as $post ) {
            setup_postdata( $post );
            $output .= get_the_title();
            $output .= '<br/>';
        }
        wp_reset_postdata();

        return $output;
    }
}

Then in home.php you could do:

<?php echo evertstrap_post(); ?>

Upvotes: 1

Related Questions