Search code examples
phpwordpressfeedshortcode

Wordpress shortcode blog feed


I am trying to create my blog feed on a home page(static page) using a shortcode.

So far I have managed to make it display titles, but I would also like it to display like 250 characters of the entry content under each displayed post title.

In other words, I just need it to display title and first few sentences.

Is it even possible?

This is the code used to create the feed.(it displays predefined number of latest posts titles inside tag)

 function getblogposts($atts, $content = null) {
       extract(shortcode_atts(array(
          'posts' => 1,
       ), $atts));

   $return_string = '<h3>'.$content.'</h3>';
   $return_string .= '<ul>';
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
   if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
      endwhile;
   endif;
   $return_string .= '</ul>';

   wp_reset_query();
   return $return_string;

SOLVED Special thanks to pmandell and gtr1971.

Complete feed.php code which creates feeds limited to 100 characters.

<?php

function getblogposts($atts, $content = null) {
   extract(shortcode_atts(array(
      'posts' => 1,
   ), $atts));

   $return_string = '<h3>'.$content.'</h3>';
   $return_string .= '<ul>';
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
   if (have_posts()) :
      while (have_posts()) : the_post();
    $return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a>';
    $return_string .= '<div class="excerpt">' . get_the_excerpt() . '</div></li>';
endwhile;
   endif;
   $return_string .= '</ul>';

   wp_reset_query();
   return $return_string;
}
function new_excerpt_more( $more ) {
    return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">[...]</a>';
}   
add_filter( 'excerpt_more', 'new_excerpt_more' );  


function custom_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 100 );
?>

Solution

  • Yes, of course this is possible. You are using a WordPress loop, so just use get_the_excerpt().

    while (have_posts()) : the_post();
        $return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a>';
        $return_string .= '<div class="excerpt">' . get_the_excerpt() . '</div></li>';
    endwhile;
    

    You can use the new_excerpt_more filter to control what displays at the end of the excerpt. Here is an example where "[...]" displays at the end of the excerpt, as a link to the post.

    function new_excerpt_more( $more ) {
        return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">[...]</a>';
    }   
    add_filter( 'excerpt_more', 'new_excerpt_more' );