Enhancing Shortcodes- A Guide to Displaying Excerpts in Your Content

by liuqiyue

How do I alter shortcode to display excerpts? This is a common question among WordPress users who want to customize their content display. Shortcodes are a convenient way to add functionality to your posts and pages, but sometimes they may not work as expected. In this article, we will guide you through the process of modifying shortcodes to display excerpts instead of full content.

In WordPress, shortcodes are used to embed various types of content, such as videos, images, and custom posts. One of the most popular shortcodes is the `[content]` shortcode, which is used to display the full content of a post or page. However, you may want to display only an excerpt of the content instead. Here’s how you can achieve this:

1. Identify the shortcode: First, you need to identify the shortcode you want to modify. In this case, it is the `[content]` shortcode.

2. Create a custom function: To display an excerpt instead of the full content, you will need to create a custom function. Open your theme’s functions.php file or create a child theme and add the following code:

“`php
function custom_excerpt_shortcode($atts, $content) {
$atts = shortcode_atts(array(
‘length’ => 55,
‘more’ => ‘Read more…’
), $atts);

$excerpt = wp_trim_words($content, $atts[‘length’], $atts[‘more’]);
return $excerpt;
}
add_shortcode(‘custom_excerpt’, ‘custom_excerpt_shortcode’);
“`

3. Use the custom shortcode: Now that you have created a custom function, you can use the `[custom_excerpt]` shortcode in your posts and pages. Replace the `[content]` shortcode with `[custom_excerpt]` and set the desired excerpt length and “Read more” text.

“`html
[custom_excerpt length=”50″ more=”Read more…”]
“`

4. Test the changes: Save your changes and visit your website to see the excerpts in action. If everything works correctly, you should see the desired number of words from the post or page content, followed by the “Read more” link.

By following these steps, you can easily alter shortcodes to display excerpts in WordPress. Remember that you can customize the excerpt length and the “Read more” text to suit your needs. Happy coding!

You may also like