简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM