Wordpress excerpt by second paragraph

前端 未结 1 1910
闹比i
闹比i 2021-01-26 00:48

How to limit the excerpt length by paragraph, not word/char count? For example, excerpt shows only first two paragraphs, no matter how long the paragraphs are.

Thanks in

相关标签:
1条回答
  • 2021-01-26 01:13

    Here is a function that keeps HTML tags in tact, adds a "Read More" link at the end of the excerpt and trims the excerpt after the first paragraph.

    if ( ! function_exists( 'wpse0001_custom_wp_trim_excerpt' ) ) : 
    
    function wpse0001_custom_wp_trim_excerpt($wpse0001_excerpt) {
    global $post;
    $raw_excerpt = $wpse0001_excerpt;
    if ( '' == $wpse0001_excerpt ) {
    
    $wpse0001_excerpt = get_the_content('');
    $wpse0001_excerpt = strip_shortcodes( $wpse0001_excerpt );
    $wpse0001_excerpt = apply_filters('the_content', $wpse0001_excerpt);
    // Here we choose how many paragraphs do we want to cutthe excerpt at, This part thanks to Clément Malet
    $wpse0001_excerpt = "<p>$wpse0001_excerpt</p>";
        $wanted_number_of_paragraph = 2;
        $tmp = explode ('</p>', $wpse0001_excerpt);
        for ($i = 0; $i < $wanted_number_of_paragraph; ++$i) {
           if (isset($tmp[$i]) && $tmp[$i] != '') {
               $tmp_to_add[$i] = $tmp[$i];
           }
        }
    $wpse0001_excerpt = implode('</p>', $tmp_to_add) . '</p>';
    
    $wpse0001_excerpt = str_replace(']]>', ']]&gt;', $wpse0001_excerpt);
    
    $excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&raquo;&nbsp;' . sprintf(__( 'Read more about: %s &nbsp;&raquo;', 'pietergoosen' ), get_the_title()) . '</a>'; 
    $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); 
    
    //$pos = strrpos($wpse0001_excerpt, '</');
    //if ($pos !== false)
    // Inside last HTML tag
    //$wpse0001_excerpt = substr_replace($wpse0001_excerpt, $excerpt_end, $pos, 0);
    //else
    // After the content
    $wpse0001_excerpt .= $excerpt_end;
    
    return $wpse0001_excerpt;
    
    }
    return apply_filters('wpse0001_custom_wp_trim_excerpt', $wpse0001_excerpt, $raw_excerpt);
    }
    
    endif; 
    
    remove_filter('get_the_excerpt', 'wp_trim_excerpt');
    add_filter('get_the_excerpt', 'wpse0001_custom_wp_trim_excerpt');
    

    EDIT

    Thanks to the help from @ClementMalet, I was able to tweak my function to make you choose the amount of paragraphs where you want to cut the excerpt. Please check his great answer here

    0 讨论(0)
提交回复
热议问题