Displays post excerpt from either ‚the_content‘, ‚the_excerpt‘ or any custom field and also limits the number of words (defaults to 30). An ellipsis (‚…‘) is only shown if adequate – which wouldn’t be possible if we’re just using the WP function wp_trim_words()
.
/** * Post Preview Text Helper * * Displays post excerpt from either 'the_content', 'the_excerpt' or any * custom field and also limits the number of words (defaults to 30). * An ellipsis ('...') is only shown if adequate - which wouldn't be possible * if we're just using the WP function 'wp_trim_words()'. * * @example (1): echo bubdev_post_preview_text( 'the_excerpt', 10, ' [...]' ); * @example (2): echo bubdev_post_preview_text( 'my_custom_field_name', 20 ); */ function bubdev_post_preview_text( $field = 'the_excerpt', $limit = 0, $ellipsis = ' …' ) { // Set parameters to pull fields. if ( $field === 'the_excerpt' ) { $output = get_the_excerpt(); } elseif ( $field === 'the_content' ) { $output = get_the_content(); } else { global $post; $output = get_post_meta( $post->ID, $field, true ); } // Limit by number of words if a valid limit is set (positive integer). if ( is_int( $limit ) && $limit > 0 ) { $output = explode( ' ', $output, $limit + 1 ); // +1 since last element will be removed. if ( count( $output ) >= $limit ) { // Remove last element (the default ellipsis that will be replaced if necessary). array_pop( $output ); $output = implode( ' ', $output ); // If the last character is a dot or colon, remove it. $output = preg_replace( array( '/\.$/', '/,$/' ), '', $output ) . $ellipsis; } else { $output = implode( ' ', $output ); } } // Limit allowed tags. $allowed_html = array( 'a' => array( 'href' => array(), 'title' => array() ), 'br' => array(), 'em' => array(), 'strong' => array(), ); // Return output. return wp_kses( $output, $allowed_html ); }
Tags
wordpress word limit, limit number of words, trim words, trimming