Francesca
Francesca

Reputation: 28148

Output recent posts and excerpt in Wordpress, not of current page

I am trying to output recent posts plus the excerpt onto my homepage using the following code:

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

This seems to output the title and the permalink just fine, however it does not output the excerpt.

Hope someone can help

Upvotes: 0

Views: 2404

Answers (2)

Moeed Farooqui
Moeed Farooqui

Reputation: 3622

put the array in your desired custom post like this in your functions.php

$args = array(
      'supports' => array('title','editor','author','excerpt') // by writing these lines an custom field  has been added to CMS
  );

For retrieving at front end

echo $post->post_excerpt; // this will return you the excerpt of the current post

Upvotes: 2

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

try this one

<?php
        $args = array( 'post_type'=>'post',
'orderby'=>'post_date',
'post_status'=>'publish', 
'order'           => 'DESC',
'showposts' => '3' );
    $recent_posts = get_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<li><a href="' . get_permalink($recent->ID) . '" title="Look '.$recent->post_title.'" >' .   $recent->post_title.'</a>' . $recent->post_excerpt . ' </li> ';
    }
?>

Make sure your post_excerpt is not empty

If you want to add the post_excerpt then use wp_update_post

  $my_post = array();
  $my_post['ID'] = 37;// it is important
  $my_post['post_excerpt'] = 'This is the updated post excerpt.';


  wp_update_post( $my_post );

As per your request in comments i am showing you the demo to update the post by copying the post_title in the post_excerpt so here you go

<?php
        $args = array( 'post_type'=>'post',
'orderby'=>'post_date',
'post_status'=>'publish', 
'order'           => 'DESC',
'showposts' => '3' );
    $recent_posts = get_posts( $args );

    foreach( $recent_posts as $recent ){  // this foreach to add the excerpt
            $my_post = array();
  $my_post['ID'] = $recent->ID;// it is important
  $my_post['post_excerpt'] = $recent->post_content;    
  wp_update_post( $my_post );
    }

    foreach( $recent_posts as $recent ){  // this foreach to show the excerpt
        echo '<li><a href="' . get_permalink($recent->ID) . '" title="Look '.$recent->post_title.'" >' .   $recent->post_title.'</a>' . $recent->post_excerpt . ' </li> ';
    }
?>

wp_update_post

Also see wp_insert_post

Upvotes: 0

Related Questions