
How To Get Post Excerpt Within & Outside A Loop
- August 25, 2015
- Leave a comment
In WordPress, “Excerpt” is a small summary of the post. It is optional but you can use it if you are displaying summary of posts through your code. It is a far better and clean option to use instead of getting a specific length of post’s content as many people practice.
How To Enable Excerpt?
First of all, add some excerpt for your post in a text-area provided under content section of the post. If you can not see it there, then you must enable if from Screen Options. Click on the Screen Options present at the top right corner of your post’s back-end and see if the Excerpt is checked from there. If you can’t see excerpt option there, then your theme is not supporting this feature. You need to add it manually through code in your theme. Just paste the following code in your theme’s functions.php file. If you have a child theme enabled, then put it in child theme’s functions.php file:
1 2 3 4 |
function pt_add_excerpts_to_pages() { add_post_type_support( post, 'excerpt' ); } add_action( 'init', 'pt_add_excerpts_to_pages' ); |
Now refresh the back-end of the post, text-area for excerpt must be there under content section. You can add excerpt for this particular post here and save it.
Get Excerpt Within A Loop:
In a loop, you can get the excerpt of posts by simply putting the following code inside a WordPress loop for posts:
1 |
<?php the_excerpt(); ?> |
Get Excerpt Without A Loop:
If you want to show small description related to a post on a page where you don’t already have a WordPress posts loop running, you might find it difficult to get the excerpt of that post. There are just a few things which you need to do to achieve it.
In order to fetch this excerpt at front-end, just use the following lines of code. Also you need to replace $post_id with the id of your post.
1 |
<?php $excerpt = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id)); ?> |
$excerpt will then have the excerpt of that particular post whose post ID was provided.
User Comments