PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 8, 2022

[FIXED] Get a limited, text-only excerpt from a WordPress post?

 February 08, 2022     arrays, foreach, function, php, wordpress     No comments   

Issue

I'm using "The Loop" in my own theme template to get the last three posts from WordPress.

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

    <!-- DATE -->
    <div class="date">
    <?php the_time('m F Y');?>
    </div>

    <!-- TITLE -->
    <div class="title">
    <?php the_title(); ?>
    </div>

    <!-- SNIPPET -->
    <div class="content">
    <?php the_excerpt(); ?>
    </div>

<?php endforeach; ?>

Everything is working fine - except the_excerpt(). I need about 15-20 words of plain text from the post to show as a preview, instead of the full excerpt or the entire post content body. How do I go about doing this?


Solution

You could try using something like this to grab the first 20 words of the post if there is no excerpt available.

$content = get_the_content();
echo substr($content, 0, 20);


Answered By - Tianbo84
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing