0

In my WordPress website, I want to show a short text of each blog_post on the custom blog template. I want to show a Read More button with a link to the post at the end so a user can click on that link and view the full post.

But I am always getting the whole post instead of its summary.

Here is my code:

$moreLink = '<a href="' . the_permalink() . '"> Read More...</a>';
$wp_query = new WP_Query();
while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

<h2><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php echo wp_trim_words( the_content(), 55, $moreLink); ?>
<?php endwhile; ?>

I have tried different codes instead of wp_trim_words(the_content(), 55, $moreLink); found online with no luck. Even I have used the same line of code on another custom template and it is working fine. However, with this template, it is not working.

Am I doing any mistake in my code?

3

The problem lies in this line:

<?php echo wp_trim_words( the_content(), 55, $moreLink); ?>

You call the_content function in there. This function prints all the content and doesn't return anything. It means that you print the content, and then pass an empty string to the wp_trim_words.

It should be:

<?php echo wp_trim_words( get_the_content(), 55, $moreLink); ?>

Be careful because, as described in codex, get_the_content() does not pass the content through the 'the_content' filter. This means it won't execute shortcodes. If you want to get exactly what the_content() prints, you have to use

<?php
$my_content = apply_filters( 'the_content', get_the_content() );
echo wp_trim_words( $my_content, 55, $moreLink);
?>

I suggest to also use wp_strip_all_tags(), otherwise you may have problems with open tags that have been trimmed.

Full example:

<?php
$my_content = apply_filters( 'the_content', get_the_content() );
$my_content = wp_strip_all_tags($my_content);
echo wp_trim_words( $my_content, 55, $moreLink);
?>
  • It works but instead of the actual content, it shows me the post shortcode like this. – teccraft Mar 8 '19 at 8:45
  • @Mr. Cariol Thanks for your answer. The solution you provided is working fine. – teccraft Mar 8 '19 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.