WordPress | Get title and description from posts dynamically

| By Webner

In wordpress we can get title from post title and description from post content area dynamically:

$id = get_the_ID();                                          //get the post id.
$title = get_the_title($id);                                //get title from the post.
$content = get_post_field('post_content', $id);            // Get all content from post content area.
$trimmed_content = wp_trim_words( $content, 20, '....' ); // This function trims text to a certain number of words and returns the trimmed text.

Now we can use these variables in our code (like if you have a summary page of all the posts in which you want to use title of latest post as page title and want to show first 20 words of the content):

<title> <?php echo $title; ?> </title>
<meta name="description" content="<?php echo $trimmed_content; ?>"/>

Example of title and description in a google search:


Leave a Reply

Your email address will not be published. Required fields are marked *