Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 >';        $output .= implode(' ', $firsthalf) . '<span>...see more</span>';        $output .= '<span>';        $output .= ' ' . implode(' ', $secondhalf);        $output .= '</span>';        $output .= '</p>';    } else {        $output = '<p>'  .   $excerpt . '</p>';    }    return $output;}
Enter fullscreen modeExit fullscreen mode

Required CSS
CSS to simply hide elements when needed

.excerpt-full.hide {display: none;}.see-more-text.hide {display: none;}
Enter fullscreen modeExit 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 modeExit fullscreen mode

Using the function in simple shortcode example

function display_post(){    $rand_post = get_post('7');    print_r($rand_post);    $output = '<div>';    $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 modeExit 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Cairo, Egypt
  • Work
    Frontend Developer at Elegant Themes
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp