1
votes

I want to know how to use Wordpress get recents posts inside the post area?

I have this code from the WordPress website for getting the recent posts:

 wp_get_recent_posts( $args, $output);

If i echo this function inside the post page body (place where i write my post) i get only the exact php code showing as a text?

    <h2>Recent Posts</h2>
<ul>
<?php
    $args = array( 'numberposts' => '5' );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a> </li> ';
    }
?>
</ul>

The other code for showing the recent 5 posts also render to the post page as text and i don't know why?

How to use it correctly?

1
What do you mean only text string output?Anigel
How are you looking to format the posts ie.. title, excerpt, readmore etc...Joe Buckle
Hi, I edited my question, when you write <?php echo "Hello"; ?> you get Hello, put when i write this code inside the post are (where to write your post content and html from dashboard) i get the exact <?php echo "Hello"; ?> on the page when i view the post page on the browser.Aneed Hamas

1 Answers

1
votes

I'm not certain about what you mean with "post area". With "string text output" I presume you mean unformatted text links in a list.

If you need to have more control over how to format the output (to make it more like a regular post listing for example), use a regular WP Query for this. You can get the 5 latest blog entries with these arguments:

$recent_args = array(
    "posts_per_page" => 5,
    "orderby"        => "date",
    "order"          => "DESC"
);      

$recent_posts = new WP_Query( $recent_args );

And to loop through them just use the regular WordPress main loop structure:

if ( $recent_posts -> have_posts() ) :
    while ( $recent_posts -> have_posts() ) :

    $recent_posts -> the_post();

    // ... Use regular 'the_title()', 'the_permalink()', etc. loop functions here.

    endwhile;
endif;