Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

How to bend the HTML output if a custom excerpt is pulled from an advanced custom field plugins WYSIWYG field

I've a custom excerpt function to get an excerpt from an advanced custom fields WYSIWYG field. The function inside the functions.php looks like:

function custom_field_excerpt($title) {
    global $post;
    $text = get_field($title);
    if ( '' != $text ) {
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $excerpt_length = 35; // 20 words
        $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return apply_filters('the_excerpt', $text);
}

the function is called in the html by:

<p class="bran-hn news-excerpt"><?php echo custom_field_excerpt('news_post'); ?></p>

the result looks like:

<p class="bran-hn news-excerpt"></p>
<p>Worf, It's better than music. It's jazz. Mr. Crusher, ready a collision course with the Borg ship. This is not about revenge. This is about justice. The Federation's gone; the Borg is everywhere! In all trust, [...]</p>
<p></p>

But i would have expected and head for:

<p class="bran-hn news-excerpt">Worf, It's better than music. It's jazz. Mr. Crusher, ready a collision course with the Borg ship. This is not about revenge. This is about justice. The Federation's gone; the Borg is everywhere! In all trust, [...]</p>

I guess it is caused by html tags added by the WYSIWYG editor. But adding the line:

$text = strip_tags( $text );

also hasn't helped. Anyone has an idea how to solve that issue? Best regards Ralf

1 Answer

Ok I finally found a solution. First you need to deactivate the auto paragraph tag for the acf wysiwyg field (the call differs from the regular wp one)

remove_filter ('acf_the_content', 'wpautop');

and in the excerpt function the field query has to be modified either:

$text = the_field($title, false, false);

Then everything is working as expected html markup wise ;)