1

I tried echoing get_the_excerpt(1), on different locations outside the loops:

  • somewhere in footer.php
  • somewhere in header.php

(The post with ID 1 has no defined excerpt btw, so I was hoping for the auto-generated ones to came out)


The one in footer.php printed the stuff just fine, but the one in header.php somehow printed nothing (blank).

May I ask for simple explanation on how such thing could happen? And a workaround to make auto-generated excerpt printed correctly on both locations.

Thank You.

  • Do you use a secondary (custom) loop in the main template? In that case you'll have to call wp_reset_postdata(); before you can use get_the_excerpt() in the footer. – Scott Mar 2 '17 at 14:35
0

Outside the loop you could try something like this:

$post_id = 1;
$myexcerpt = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));

echo $myexcerpt;
  • I tried your code, and it's giving me blanks on both locations. The post have no defined excerpt, so post_excerpt is empty, which is probably the reason why your code is giving blanks... – Assistant-kun Mar 2 '17 at 9:32
  • You have to change it to the post that has the excerpt. Can you test with one that actually has an excerpt? – rudtek Mar 2 '17 at 9:38
  • both your code and simple get_the_excerpt(1) gives the right stuff if the post_excerpt is not empty. But unfortunately, I'm looking for solution for when has no defined excerpt (post_excerpt is empty). – Assistant-kun Mar 2 '17 at 10:13
  • What do you want it to do when excerpt is empty? – rudtek Mar 2 '17 at 16:35
0

So you are basically also looking for a fallback in case your excerpt is empty? I suppose this question/answer could be helpful for you: "get_the_excerpt() with fallback like the_excerpt()". It describes, how to build your own "excerpt" in case there is none – like this:

$excerpt = get_the_content();
$excerpt = esc_attr( strip_tags( stripslashes( $excerpt ) ) );
$excerpt = wp_trim_words( $excerpt, $num_words = 55, $more = NULL );

In your case you would probably add the ID to it: $excerpt = get_the_content(1);. I don't know if your SE privileges allow this, but should probably add "I'm looking for a solution for when has (the article) no defined excerpt / the post_excerpt is empty" to your question to clarify what you are actually looking for…

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.