WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] How to Display First 20 Characters of a Post?

[Resolved] How to Display First 20 Characters of a Post?

  • Hi,

    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):

    <?php
    //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:

    <?php
    $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?

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • MichaelH

    @michaelh

    $string = $post->post_content;

    or

    $string = get_the_content('');

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

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘[Resolved] How to Display First 20 Characters of a Post?’ is closed to new replies.
Skip to toolbar