How to Create a Custom Excerpt Function in WordPress that Preserves HTML Links

WordPress is a versatile platform that allows developers to customize various aspects of their websites. One common customization is creating custom excerpts for posts. Excerpts are brief summaries of posts, and sometimes, you may want to preserve HTML links within these summaries while limiting the content to a certain number of words.

In this tutorial, we will create a function that does just that.

The Custom Excerpt Function

First, we need to create a custom function that retrieves the post content, preserves any HTML link tags, and displays only the first 50 words. Add the following function to your theme’s functions.php file or create a custom plugin for it:

function custom_excerpt_with_links($post_id, $word_count = 50) {
    // Get the post content
    $text = get_the_content('', '', $post_id);

    // Preserve link tags by replacing them with placeholders
    $content = preg_replace('/<a\b[^>]*>(.*?)<\/a>/i', 'LINKPLACEHOLDER$1LINKPLACEHOLDER', $text);

    // Strip all tags except link placeholders
    $content = strip_tags($content);

    // Replace link placeholders with original links
    $content = preg_replace('/LINKPLACEHOLDER(.*?)LINKPLACEHOLDER/i', '<a href="#">$1</a>', $content);

    // Split content into words
    $words = explode(' ', $content);

    // Get the first n words
    $first_n_words = array_slice($words, 0, $word_count);

    // Join the first n words into a string
    $excerpt = implode(' ', $first_n_words);

    // Append ellipsis if content has more than the specified word count
    if (count($words) > $word_count) {
        $excerpt .= '...';
    }

    return $excerpt;
}

Using it on your WordPress File

To use this function in your template files, you need to call it with the post ID. Here’s an example of how to use the function within the loop of a template file:

<?php
if (have_posts()) :
    while (have_posts()) : the_post();
        $post_id = get_the_ID(); // Get the current post ID
        echo custom_excerpt_with_links($post_id);
    endwhile;
endif;
?>

That’s it!

Leave a Comment

trabzon escort yalova escort Samsun escort izmit escort nazilli escort