<?php $the_query = new WP_Query( 'page_id=46' ); ?> <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> <?php the_excerpt(); ?> <?php endwhile;?>
<?php the_excerpt_max_charlength(140); function the_excerpt_max_charlength($charlength) { $excerpt = get_the_excerpt(); $charlength++; if ( mb_strlen( $excerpt ) > $charlength ) { $subex = mb_substr( $excerpt, 0, $charlength - 5 ); $exwords = explode( ' ', $subex ); $excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) ); if ( $excut < 0 ) { echo mb_substr( $subex, 0, $excut ); } else { echo $subex; } echo '[...]'; } else { echo $excerpt; } } ?>
เอามารวมกัน
<?php $the_query = new WP_Query( 'page_id=46' ); ?> <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> // เอาอันนี้ออก <?php the_excerpt(); ?> <?php endwhile;?> <?php the_excerpt_max_charlength(140); function the_excerpt_max_charlength($charlength) { $excerpt = get_the_excerpt(); $charlength++; if ( mb_strlen( $excerpt ) > $charlength ) { $subex = mb_substr( $excerpt, 0, $charlength - 5 ); $exwords = explode( ' ', $subex ); $excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) ); if ( $excut < 0 ) { echo mb_substr( $subex, 0, $excut ); } else { echo $subex; } echo '[...]'; } else { echo $excerpt; } } ?>
หรือ
ใน functions.php
function excerpt($limit) { $excerpt = explode(' ', get_the_excerpt(), $limit); if (count($excerpt) >= $limit) { array_pop($excerpt); $excerpt = implode(" ", $excerpt) . '...'; } else { $excerpt = implode(" ", $excerpt); } $excerpt = preg_replace('`\[[^\]]*\]`', '', $excerpt); return $excerpt; } function content($limit) { $content = explode(' ', get_the_content(), $limit); if (count($content) >= $limit) { array_pop($content); $content = implode(" ", $content) . '...'; } else { $content = implode(" ", $content); } $content = preg_replace('/\[.+\]/','', $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); return $content; }
นำไปใช้
<?php echo excerpt(25); ?>
ตัวอย่าง หน้าที่นำไปใช้ (โค๊ดนี้ดึงหน้า page ที่ต้องการ แล้ว กำหนดขนาดความยาวข้อความ)
<?php $the_query = new WP_Query( 'page_id=46' ); ?> <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> <?php echo excerpt(25); ?> <?php endwhile;?>