7

I'm using the_excerpt on my index page. I'm also using a dropcap shortcode at the beginning of each of my posts. On the index page, the posts will not display the letter with the dropcap shortcode around it. If my post beings with the word "Dog" the index page displays "og". How do I get shortcodes to work when using the_excerpt?

Shortcode

function drcap ($atts, $content = null) {
    return '<div class="dropcap">' . do_shortcode($content) . '</div>';
}

add_shortcode('dropcap', 'drcap');

4 Answers 4

12

Paste this in your theme's functions.php file

add_filter( 'the_excerpt', 'shortcode_unautop');
add_filter( 'the_excerpt', 'do_shortcode');
2

In the auto-generated excerpt shortcodes will be removed by Wordpress:

An auto-generated excerpt will also have all shortcodes and tags removed. It is trimmed down to a word-boundary and the default length is 55 words.

Anyhow, if you use the manual excerpt field for your post, it works.

2

Here's a solution for including shortcode output within Wordpress's auto-generated excerpts:

add_filter('the_excerpt', 'do_shortcode');
remove_filter('get_the_excerpt', 'wp_trim_excerpt', 10);
add_filter('get_the_excerpt', 'my_custom_wp_trim_excerpt', 99, 1);
function my_custom_wp_trim_excerpt($text) {
    if(''==$text) {
        $text= preg_replace('/\s/', ' ', wp_strip_all_tags(get_the_content('')));
        $text= explode(' ', $text, 56);
        array_pop($text);
        $text= implode(' ', $text);
    }
    return $text;
}

This implementation assumes a word-length of 55.

Hope it helps someone.

1
  • Thanks much. The accepted solution doesn't work for me--and might just plain not work for "modern" (2016+) WordPress. This does what I need, though. Mar 16, 2016 at 19:33
1

Also, add these 2 lines to your functions.php file for complete and comprehensive results:

add_filter('get_the_excerpt', 'shortcode_unautop');
add_filter('get_the_excerpt', 'do_shortcode');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.