0

From this thread: the_excerpt and shortcodes I pulled this snippet of code from @Programmer Dan that is working well to include executed shortcodes in autogenerated excerpts

    add_filter('the_excerpt', 'do_shortcode');
remove_filter('get_the_excerpt', 'wp_trim_excerpt', 10);
add_filter('get_the_excerpt', 'my_custom_wp_trim_excerpt', 99, 1);
function my_custom_wp_trim_excerpt($text) {
    if(''==$text) {
        $text= preg_replace('/\s/', ' ', wp_strip_all_tags(get_the_content('')));
        $text= explode(' ', $text, 56);
        array_pop($text);
        $text= implode(' ', $text);
    }
    return $text;
}

My problem is I can't figure out how to also add either button or text link for read more going back to original article.

0

If you take a look at the source code of get_the_excerpt you see that there actually two arguments passed to the filter: the excerpt text and the post object. Your are only passing the text, while you need the post object to know the permalink.

So you should change these lines:

add_filter('get_the_excerpt', 'my_custom_wp_trim_excerpt', 99, 1);
function my_custom_wp_trim_excerpt($text) {

to:

add_filter('get_the_excerpt', 'my_custom_wp_trim_excerpt', 99, 2);
function my_custom_wp_trim_excerpt($text,$post) {

Now you have the post object available in your filter function and you can use get_permalink($post) to retrieve the link to the post and do whatever you like with it. For instance like this:

function my_custom_wp_trim_excerpt($text) {
    if(''==$text) {
        $text= preg_replace('/\s/', ' ', wp_strip_all_tags(get_the_content('')));
        $text= explode(' ', $text, 56);
        array_pop($text);
        $text= implode(' ', $text);
    }
    $text = $text . '<a href="' . get_permalink($post) . '">Link to post</a>';
    return $text; }
  • Thank you, that is very informative and helpful, but I'm still not clear on just how to use 'get_permalink($post)' in this scenario -- together with the text output how would I add that to the string that gets returned to add some html ... something along the lines of ' $something = $something . <a href="' . get_permalink($post). '"><button class="read-more-btn" type="button" value="read_more">Read More</button></a>'; – Trip Vendors Inc Jun 23 '17 at 9:40
  • Yes. get_permalink returns a string and you can concatenate that to your excerpt including any html you like before returning the completed string. – cjbj Jun 23 '17 at 9:43
  • Hi - I just don't know how to add that to the above code... – Trip Vendors Inc Jun 23 '17 at 10:20
  • I have updated the answer with some basic php. – cjbj Jun 23 '17 at 10:30

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.