0

I'm using wp_trim_excerpt which is working perfectly but I want to strip the links contained in the the_excerpt (using get_the_content), I've looked online and tried many solutions to get the thing to work and hoping someone can help point me in the right direction.

My working code looks like this:

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 );
    }
    $text = preg_replace("/<img[^>]+\>/i", "", $text); 
    $buttonmore = '<p><a class="button right" href="'. get_permalink($post->ID) . '"> Read the full article...</a></p>';
    return $text . " " . $buttonmore;
}

Not working (I've added strip_tags( get_the_content() )

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', strip_tags(get_the_content()) );
        $text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
    }
    $text = preg_replace("/<img[^>]+\>/i", "", $text); 
    $buttonmore = '<p><a class="button right" href="'. get_permalink($post->ID) . '"> Read the full article...</a></p>';
    return $text . " " . $buttonmore;
}
2

Add another preg_replace. Something like:

$text = preg_replace('/<a href=\"(.*?)\">(.*?)<\/a>/', "", $text);
  • Worked an absolute treat! Thanks for taking the time to help me. – Simon Hayter Aug 26 '15 at 7:46
  • Obvious caution needed for a tags without the href attribute as the first element <a class="xzy" href="abc"... – Andy Gee Dec 7 '16 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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