Support » Themes and Templates » recent articles box

  • 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.

Viewing 1 replies (of 1 total)
  • Michael


    Forum Moderator

    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)

Viewing 1 replies (of 1 total)
  • The topic ‘recent articles box’ is closed to new replies.