• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP SITES

2785

Original Genesis & WooCommerce Tutorials & 6000+ Guaranteed Code

Snippets

  • Try Premium
  • Log in

Create Excerpt of Custom Field Text With Read More Link & Word Limit

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:

  • add_action hook
  • conditional tag
  • get_post_meta
  • sprintf
  • variables

Custom Fields

Reader Interactions

Leave a Reply Cancel reply

You must be logged in to post a comment.

Primary Sidebar

Code written by Brad Dalton specialist for Genesis, WooCommerce & WordPress theme customization. Read More…

Advertise · WPEngine · Genesis · Log in

  • Access Problems
  • Account Details
  • Consulting
  • Tags
 

Loading Comments...
 

You must be logged in to post a comment.