Felix
Felix

Reputation: 1583

Wordpress: get posts and show 50 first characters

I want to show the three latest posts with the 50 first characters. And a "read more" link at the end. Like this:

My first post

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vulputate. Read more...

My second post

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vulputate. Read more...

My third post

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vulputate. Read more...

Do I use get_posts? How do I do it?

Upvotes: 1

Views: 5838

Answers (3)

Simon Chan
Simon Chan

Reputation: 41

You can use this without the going to functions.php page.

<?php
$args = array( 'numberposts' => 1 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_content_rss('', TRUE, '', 33); ?> <a class="continue" href="<?php     the_permalink() ?>">Continue Reading &raquo;</a>
<?php endforeach; ?>

Upvotes: 4

Felix
Felix

Reputation: 1583

This became my solution:

In the template:

<?php
$args = array( 'numberposts' => 3 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); 
?> 

<h2 class="news"><?php the_title(); ?></h2>
<?php the_excerpt(); ?>

<?php endforeach; ?>

In functions.php:

function new_excerpt_more($more) {
       global $post;
    return '... <a href="'. get_permalink($post->ID) . '">Read more</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');


function custom_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Upvotes: 4

Sorcy
Sorcy

Reputation: 2613

Yes you use get_posts:

$options = array(
    'number_of_posts' => 3
);

$myposts = get_posts($options);
foreach( $myposts as $post ) {
    setup_postdata($post);
    echo '<h2>' . the_title . '</h2>';
    echo the_content();
}

You could use something like "$mycontent = get_the_content()" and then manipulate it with phps substring, but honestly: DO NOT DO IT!

For your read more function Wordpress has the perfectly fine more tag in the editor, which will automagically work for you, if you try something like this:

foreach( $myposts as $post ) {
    setup_postdata($post);
    echo '<h2>' . the_title . '</h2>';
    echo the_excerpt();
    echo '<a href="' . the_permalink() . '">More &raquo;</a>';
}

Upvotes: 1

Related Questions