xxxxxxxxxx
/**
* Returns a custom excerpt with a specific number of words.
*
* @link https://www.wpexplorer.com/custom-excerpt-lengths-wordpress/
* @param array The function arguments.
*/
function wpexplorer_get_post_excerpt( $args = '' ) {
if ( ! is_array( $args ) ) {
$args = [
'length' => $args,
];
}
// Default arguments.
$defaults = [
'post' => '',
'length' => 40,
'readmore' => false,
'readmore_text' => esc_html__( 'read more', 'textdomain' ) . ' →',
'custom_excerpts' => true,
];
// Parse arguments, takes the function arguments and combines them with the defaults.
$args = wp_parse_args( $args, $defaults );
// Apply filters to the arguments.
$args = apply_filters( 'wpexplorer_post_excerpt_args', $args );
// Extract arguments to make it easier to use below.
extract( $args );
// Get the current post.
$post = get_post( $post );
// Not a valid post.
if ( ! is_a( $post, 'WP_Post' ) ) {
return;
}
// Get the current post id.
$post_id = $post->ID;
// Check for custom excerpts and display them in full without trimming.
if ( $custom_excerpts && has_excerpt( $post_id ) ) {
$output = wp_kses_post( $post->post_excerpt );
}
// No custom excerpt...so lets generate one.
else {
// Generate an excerpt from the post content once shortcodes have been stripped out.
// Note: If your site is using a shortcode based page builder such as WPBakery you will need
// to write a complex function to grab the text from the first text block like we do in our Total theme.
$output = wp_trim_words( strip_shortcodes( $post->post_content ), $length );
}
// Add the readmore text to the excerpt if enabled.
if ( ! empty( $output ) && $readmore ) {
$output .= '<a href="' . esc_url( get_permalink( $post_id ) ) . '">' . esc_html( $readmore_text ) . '</a>';
}
return apply_filters( 'wpexplorer_post_excerpt', $output, $args );
}