I’m using a custom function to create a shortcode that displays the latest blog post on the home page of a template. But I’m trying to NOT have it display any images.
I know I can use the Advanced Excerpt plugin to have it remove images, but the issue is that it will also remove images from the index.php feed which I want to keep which is using the_excerpt()
in the template.
Here’s my custom function that creates the shortcode:
function my_recent_news()
{
global $post;
$html = "";
$my_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 4
));
if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
$html .= "
<article>
<span class="date">" . get_the_date() . "</span>
<h2><a href="" . get_permalink() . "">" . get_the_title() . "</a></h2>
" . get_the_excerpt() . "
</article>
";
endwhile;
endif;
wp_reset_query();
return $html;
}
add_shortcode( 'news', 'my_recent_news' );
I’ve posted something about this before:
but the solution was to use the Advanced Excerpt plugin, but for this I am trying to use the excerpt on the home and the blog feed page but I want to preserve the img
markup on the blog feed and remove the img tag from the custom shortcode.
I’ve tried to used just the_excerpt()
in that custom shortcode function, but that just seems to break the whole function and display some really odd stuff.
I’m not too sure if I need to have a filter somewhere to strip that out or what. I’m also not sure that if I do need a filter, where that would go? Before the loop, after the loop, or does it need it’s own constructed argument?
If you read the Codex entry for
get_the_excerpt()
, you will find this:The
wp_trim_excerpt()
function:So, you could either re-apply
wp_trim_excerpt()
to theget_the_excerpt
filter, or else just output it directly:Ok, so I did more digging and testing and I found by using
strip_tags()
basically removes any formatting withinget_the_excerpt()
.Here’s my updated code:
I added the
<a>
to preserve any hyperlinks within the excerpt of the post to display.With this, I can preserve the markup with the blog feed page along with using the Advanced Excerpt plugin to assist with trimming the length and what not.