recent articles box (2 posts)

  1. nigelll
    Posted 3 years ago #

    Im trying to make a small box that displays the 3 latest posts in the following format:

    This is the title of the first post Read more »
    This is the title of the second post Read more »
    This is the title of the third post Read more »

    The read more links will not point to the individual posts, but to the main blog page. This is because the posts will mostly be short announcements.

    Also the box is pretty small, so space will be limited. I want the title of the post to cut off after a specific number of characters like this:
    This post title is too lon... Read more »

    I know the solution will probably be pretty simple, but I'm somewhat new to this so please bear with me...

    Thank you for your time.

  2. Michael
    Forum Moderator
    Posted 3 years ago #

    you will need to create a secondary loop with either get_posts() or WP_Query(), and use a function to truncate any post titles;

    <?php $recent = get_posts( 'posts_per_page=3' );
    if( $recent ) foreach( $recent as $post ) {
    setup_postdata( $post ); ?>
    <span class="recent-date"><?php the_time('d.m.Y'); ?></span>
    <span class="recent-title"><?php $limit = 20; $text = get_the_title();
          if (str_word_count($text, 0) > $limit) {
              $words = str_word_count($text, 2);
              $pos = array_keys($words);
              $text = substr($text, 0, $pos[$limit]) . '...';
          echo $text; ?>
    <a href="<?php echo home_url(); ?>"> Read more »</a></span>
    <?php }
    wp_reset_postdata(); ?>

    using spans for the time and title; assuming that the main blog page is the home page.
    (totally untested)


Topic Closed

This topic has been closed to new replies.

About this Topic