I am trying to check for an excerpt and if it doesn’t exist then show the content but trimmed. Currently nothing is showing.
<?php if (has_excerpt() ): ?>
<p><?php echo get_the_excerpt(); ?></p>
<?php else: ?>
<p><?php echo wp_trim_words(get_the_content(), 25); ?></p>
<?php endif; ?>
However, if I simply do the below then I see content. Is there an issue with my above code? This is running inside a WP_Query loop
<p><?php echo wp_trim_words(get_the_content(), 25); ?></p>
The loop:
<?php $args = array(
'post_type' => 'post',
'posts_per_page' => 8,
'category__not_in' => 4
);
$latestPosts = new WP_Query( $args );
?>
<?php if ($latestPosts->have_posts() ): ?>
<ul>
<?php while ($latestPosts->have_posts() ): $latestPosts->the_post(); ?>
<li>
//The excerpt code etc. goes here
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</ul>
<?php endif; ?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
So we already resolved the issue via the comments, but I thought I should explain something:
has_excerpt() returns ! empty( $post->post_excerpt ) if the post has a custom/manual excerpt, so if the function is returning true when it should be false, then it’s likely because the length of the excerpt in the database is > 0, e.g. when the value is a whitespace — empty( ' ' ) = false. (But note that empty( '0' ) or empty( 0 ) is true)
So if that’s the case, then you should fix the post_excerpt value in the database so that the function returns the expected value.
But as I said in the comment, I’m not sure why the excerpt was imported with all that whitespace, so I could only guess they were added during export or maybe the import, via a filter.
Anyway, I hope this answer helps! 🙂
Method 2
Iggy!
With WP functions, typically speaking the get_ before the function signifies that the call is made outside of the loop, and as such you need to declare an object ID within the brackets, like so:
get_the_excerpt( $post->ID )
If you’re using this function within the object loop, you should just call:
the_excerpt()
Which doesn’t require the object ID, because that is already making up the query.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0