The code in this tutorial enables you to create a excerpt of your custom field text and add a read more link to it just like a post excerpt. You can also limit the amount of words in the text.
Here’s the text added to a custom field named key :
And here’s the output on the front end which shows the text has been limited to 6 words and a read more link added :
The Code
The following code snippet, which produces what you see in the above screenshot, uses wp_trim_words which contains 3 parameters.
wp_trim_words( $text, $number, $more );
The 1st parameter $text equals the value for the custom field.
The 2nd parameter $number equals 5 which is the word limit.
The 3rd parameter $more equals the read more link.
Swap out loop start in the following code with any WordPress or theme specific hook.
add_action( 'loop_start', 'add_custom_types' );
function add_custom_types() {
if ( ! is_singular() )
$text = get_post_meta( get_the_ID(), 'key', true );
$number = '6';
$more = sprintf( ' .... <a href="%s" class="more-link" rel="bookmark">' . __( 'Read More' ) . '</a>', esc_url( get_permalink() ) );
$output = wp_trim_words( $text, $number, $more );
echo '<p>' . $output . '</p>';
}
The above code uses the following functions:
Leave a Reply