Reputation: 2031
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
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();
}
}
$post->key_name
within this loop. PHP: Getting data out of an objectUpvotes: 0
Reputation: 468
I've seen this sometimes in WordPress where echo
ing 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