I'm having an issue related to the_excerpt
filter. For some reason, if the post being displayed in a posts listing contains only shortcodes, it will execute those shortcodes no matter what.
What I would like is to either display the content if it's an enclosing shortcode, or strip it out altogether if it's a self-closing one and return an empty string if that's the case.
I'm using this function to strip out all shortcodes (because strip_shortcodes($content))
also didn't work:
add_filter('the_excerpt', 'my_custom_excerpt' );
function my_custom_excerpt() {
global $post;
$post_excerpt = $post->post_excerpt != "" ? $post->post_excerpt : strip_tags($post->post_content);
$excerpt_more = "...";
$excerpt_length = 30;
$clean_excerpt = strpos($post_excerpt, '...') ? current(explode($post_excerpt, $excerpt_more, '1')) : $post_excerpt;
$clean_excerpt = strip_shortcodes(preg_replace("/\[[\/]?[^\]]*\]/", "", $clean_excerpt));
$excerpt_word_array = explode(' ', $clean_excerpt);
$word_count = count($excerpt_word_array);
$excerpt_word_array = array_slice($excerpt_word_array, 0, $excerpt_length);
if ($word_count > $excerpt_length) {
$excerpt = implode(' ', $excerpt_word_array) . $excerpt_more;
}
else {
$excerpt = implode(' ', $excerpt_word_array);
}
return $excerpt;
}
I have a custom shortcode that generates an image slider and after the html, it outputs a script tag with the slider init function (basic stuff).
In the post excerpt I'm seeing the javascript output - which is super strange.
Accessing the posts, I see the slider running as expected, the html structure looks fine.
Anyway.. if you have any pointers to why this is happening and possible fixes, it would be great.
PS : the code above works, the if statement is ok from my tests, the issue is only when the post contains only shortcodes is when things get weird. If I append something to the excerpt variable, then it works as expected and prints out only what i've appended.
So if I do
else {
$excerpt = implode(' ', $excerpt_word_array)."something";
}
I see the excerpt for the post that contains only my shortcode print out "something". Without it, as mentioned before, it prints the javascript content. Which again, is weird.