Forums

Custom Excerpt Text in Functions.php (5 posts)

  1. popstalin
    Member
    Posted 1 year ago #

    I want to create custom excerpt text for a custom template using my functions.php file. Is it possible? Instead of having "...read more", I need "Read and Comment (0)" with the comment numbers showing in the excerpt read more link. Is this possible? I'm using the_excerpt, not custom excerpts.

    TIA!

  2. richarduk
    Member
    Posted 1 year ago #

    Here's a starting point.

    function new_excerpt_more($post) {return '<span class="more-excerpt"><a class="more-link-excerpt" href="'. get_permalink($post->ID) . '">' . '[...]' . '</a></span>';}
    add_filter('excerpt_more', 'new_excerpt_more');
    /*
    Changes [...] after the default excerpt but NOT when you manually enter an excerpt into the excerpt box beneath a post (currently anything entered into the excerpt box is displayed without being followed by  [...]  )
    http://codex.wordpress.org/Template_Tags/the_excerpt
    */
  3. popstalin
    Member
    Posted 1 year ago #

    Thanks richarduk! I've seen that but my problem is, I need it to be custom. I don't want the other excerpts I'm using picking that up as well. Does that make sense?

  4. richarduk
    Member
    Posted 1 year ago #

    How about surrounding it with a conditional? If is category 5, if is single etc.

  5. popstalin
    Member
    Posted 1 year ago #

    That may work but a co-worker and I created some PHP magic with the following:

    <?php
        $content = $post->post_content;
        $content = strip_shortcodes($content);
        $content = str_replace(']]>', ']]>', $content);
        $content = strip_tags($content);
        $excerpt_length = 35;
        $words = explode(' ', $content, $excerpt_length + 1);
        if(count($words) > $excerpt_length) :
            array_pop($words);
            array_push($words, '…');
            $content = implode(' ', $words);
        endif;
    
        echo $content;
    ?> <a href="<?php the_permalink(); ?>">Read and Comment (<?php echo comments_number('0', '1', '%'); ?>)</a>

    It works for what I need and may well work for others too. This isn't in the functions.php file but like I said, it works.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags