开发者

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

开发者 https://www.devze.com 2023-02-17 07:39 出处:网络
I\'m using \"The Loop\" in my own theme template to get the last three 开发者_如何学编程posts from WordPress.

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?


Avoid using substr(). Why?

substr() truncates based on character count, NOT whole words, and the last word would most likely be truncated. It could also truncate the end HTML tag(s) and return malformed HTML, screwing up the rest of your layout.

Don't re-invent the wheel!

WordPress 3.3 onwards has a new core function called wp_trim_words()

Parameter breakdown:

wp_trim_words($text, $num_words, $more);


$text
    (string) (required) Text to trim
    Default: None

$num_words
    (integer) (optional) Number of words
    Default: 55

$more
    (string) (optional) What to append if $text needs to be trimmed.
    Default: '…'

Example usages:

<?php echo wp_trim_words(get_the_excerpt(), 30, '...'); ?>

<?php echo wp_trim_words(get_the_content(), 50, '... read more &gt;'); ?>


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


try this :

Post contains images :

$content = get_the_content();
$content = apply_filters('the_content', $content);
$content = str_replace(']]>',']]&gt;', $content);
echo substr(strip_tags($content),0,100); 

and without images:

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


Put this code in functions.php

function new_excerpt_length($length) {
  return 20;}
add_filter('excerpt_length', 'new_excerpt_length');

And just call this function from your template page or index.php file

the_excerpt();
0

精彩评论

暂无评论...
验证码 换一张
取 消