Monday, January 16, 2012

Display custom text in wordpress

Display custom text in wordpress

Using modified the_excerpt() function we can display an excerpt which is not longer than a predetermined length and doesn’t cut off in mid-sentence.

To do is open functions.php file and paste the code below in it which works as a function

// Variable & intelligent excerpt length.
function print_excerpt($length) { // Max excerpt length. Length is set in characters
    global $post;
    $text = $post->post_excerpt;
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
    }
    $text = strip_shortcodes($text); // optional, recommended
    $text = strip_tags($text); // use ' $text = strip_tags($text,'< p >< a >'); ' if you want to keep some tags

    $text = substr($text,0,$length);
    $excerpt = reverse_strrchr($text, '.', 1);
    if( $excerpt ) {
        echo apply_filters('the_excerpt',$excerpt);
    } else {
        echo apply_filters('the_excerpt',$text);
    }
}

// Returns the portion of haystack which goes until the last occurrence of needle
function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}



Now you can use the print_excerpt() function in the theme files like this:

 print_excerpt(50);

1 comment:

  1. this is programming which is very helpfull for any website and programmers make softwares and applications.

    Custom Fan Page

    ReplyDelete

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off