Display 1st paragraph within Advanced Custom Field

2019-09-14 06:48发布

问题:

How do you display only the first paragraph of an advanced custom field.

  <?php the_field('lyrics'); ?>

Above is what i use to display the full text.

回答1:

add_filter( 'wp_trim_excerpt', 'my_custom_excerpt', 10, 2 );
function my_custom_excerpt($text, $raw_excerpt) {
    if( ! $raw_excerpt ) {
        $content = apply_filters( 'the_content', get_the_content() );
        $text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
    }
    return $text;
}

try this code will help you to show first 55 character of your first paragraph.

Grab the first paragraph of each post

second option:

function custom_field_excerpt() {
global $post;
$text = get_field('news');
if ( '' != $text ) {
    $start = strpos($text, '<p>'); // Locate the first paragraph tag
    $end = strpos($text, '</p>', $start); // Locate the first paragraph closing tag
    $text = substr($text, $start, $end-$start+4); // Trim off everything after the closing paragraph tag
    $text = strip_shortcodes( $text );
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
}
return $text;}

third option : You can use this function:

function get_first_paragraph(){
global $post;
$str = wpautop( get_the_content() );
$str = substr( $str, 0, strpos( $str, '</p>' ) + 4 );
$str = strip_tags($str, '<a><strong><em>');
return '<p>' . $str . '</p>';}

and then use in it in your loop with:

<?php echo get_first_paragraph(); ?>