DEV Community

Cover image for Expandable WordPress post excerpt
mohamed atta
mohamed atta

Posted on • Edited on

2 2

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more