avatar Deluxe Blog Tips About Projects

Get content before more tag in WordPress

Yesterday, I wrote a simple plugin for Deluxe Blog Tips to show a "giveaway" widget in the sidebar. That widget will get the content before more tag of the giveaway post and show it. The problem is that the excerpt functions, that we often use to get that content such as the_excerpt() or the_content( $more ), don't work! After digging more into WordPress core I found a solution, and in this post I'll show you how to get the content before more tag that works in any situation!


More Tag

First, let's go through 2 common approaches that we often use:

Using the_excerpt() function

This function checks for $post->post_excerpt (the content you entered in the Excerpt meta box under main editor) and display that value. Unfortunately, I don't use post excerpt. So that fails.

Using the_content() function

This function works nearly perfectly:
- In single post page, it shows all content
- In non-single post page, it shows the content before more tag

As you see it doesn't work consistently. I want it display the content before more tag always! I need another solution.

My own hack for more tag

When I looked into the code of get_the_content() function (it's used internally inside the_content()), I found that the function uses a global variable $more to check whether or not display the full content.

So what I need to do is changing the value of this variable to false to force get_the_content() function always returns the content before more tag, and after displaying just reset it.

The code snippet is quite simple as follow:

global $more;
$temp = $more;
$more = false;
echo '<div class="giveaway-excerpt">' . get_the_content( '' ) . '</div>';
$more = $temp;

Now the content displayed is only the content before more tag. No extra function to strip content, no regular expression to extract content, ... We just use the built-in WordPress function to do to that.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Comments