DEV Community

Cover image for Expandable WordPress post excerpt
mohamed atta
mohamed atta

Posted on • Edited on

Expandable WordPress post excerpt

First the PHP
Add this function in function.php

function expandable_excerpt($excerpt)
{
    $split = explode(" ", $excerpt); //convert string to array
    $len = count($split); //get number of words
    $words_to_show_first = 19; //Word to be dsiplayed first
    if ($len > $words_to_show_first) { //check if it's longer the than first part

        $firsthalf = array_slice($split, 0, $words_to_show_first);
        $secondhalf = array_slice($split, $words_to_show_first, $len - 1);
        $output = '<p class="event-excerpt" >';
        $output .= implode(' ', $firsthalf) . '<span class="see-more-text">...see more</span>';

        $output .= '<span class="excerpt-full hide">';
        $output .= ' ' . implode(' ', $secondhalf);
        $output .= '</span>';
        $output .= '</p>';
    } else {
        $output = '<p class="event-excerpt">'  .   $excerpt . '</p>';
    }
    return $output;
}
Enter fullscreen mode Exit fullscreen mode

Required CSS
CSS to simply hide elements when needed

.excerpt-full.hide {
display: none;
}
.see-more-text.hide {
display: none;
}
Enter fullscreen mode Exit fullscreen mode

Required JS
script to add/remove css classes when needed

const itemSeeMore = document.querySelectorAll(
  "p.event-excerpt> span.see-more-text"
);
if (itemSeeMore) {
  itemSeeMore.forEach((item) => {
    item.addEventListener("click", () => {
      item.classList.toggle("hide");
      item.nextElementSibling.classList.toggle("hide");
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

Using the function in simple shortcode example

function display_post()
{
    $rand_post = get_post('7');
    print_r($rand_post);
    $output = '<div class="post-wrapper">';
    $output .= '<h2>' . $rand_post->post_title . '</h2>';
    $output .= expandable_excerpt($rand_post->post_excerpt);
    $output .= '</div>';

    return $output;
}
add_shortcode('display_post', 'display_post');
Enter fullscreen mode Exit fullscreen mode

Add the short code [display_post] in you page editor

And that's it, thanks for reading the article if you want any support on it just let me know.

Top comments (0)