[resolved] How to Display First 20 Characters of a Post? (3 posts)

  1. xdesi
    Posted 6 years ago #


    Just a quick question here, in my footer I want to display the latest 3 posts, with their post title and 20 characters from their post.

    I've been able to get the three posts to display with their titles, with (copied this from another site):

    //The Query To Get Posts
    $my_query = new WP_Query('showposts=3');
    //Run the Query and Loop Through Results
    while ($my_query->have_posts()) : $my_query->the_post();
    $do_not_duplicate = $post->ID;
    //Display Post Title From Each Post
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></h2>
    /*****Need to display the first 20 characters of the post here!*****/
    <?php endwhile; ?>

    Please let me know if there is a more efficent method to the above btw, this is just going in my footer.
    Anyhow I just need help with getting the first 20 characters of the post to display, I tried using substr like:

    $string = the_content();
    $newString = substr($string, 0, 20);
    echo $newString;

    But this just echoes the content without it being trimmed at all! Can somebody please advise me on a way to do this?


  2. MichaelH
    Posted 6 years ago #

    $string = $post->post_content;


    $string = get_the_content('');
  3. xdesi
    Posted 6 years ago #

    Thanks a ton Michael, I had a feeling the_content(); was returning the post content as I wanted!

Topic Closed

This topic has been closed to new replies.

About this Topic