Using WordPress ‘get_the_content()’ PHP function

The get_the_content() WordPress PHP function retrieves the post content.

Usage

$content = get_the_content('Read more');
echo apply_filters('the_content', $content);

Parameters

  • $more_link_text (string) Optional: Content for when there is more text. Default: null
  • $strip_teaser (bool) Optional: Strip teaser content before the more text. Default: false
  • $post (WP_Post|object|int) Optional: WP_Post instance or Post ID/object. Default: null

More information

See WordPress Developer Resources: get_the_content()

Note: get_the_content() doesn’t return the same thing as what the_content displays. To achieve that, use the following code:

$content = apply_filters('the_content', get_the_content());
echo $content;

Examples

Basic Usage

Display the post content, ending with “Read more” if needed:

$content = get_the_content('Read more');
echo apply_filters('the_content', $content);

Check if the_content has content before output

Find out if the_content has content before output in functions.php and similar files:

// Inside the loop
$the_content = apply_filters('the_content', get_the_content());
if (!empty($the_content)) {
    echo $the_content;
}

// With post object by ID
$post = get_post(12); // specific post
$the_content = apply_filters('the_content', $post->post_content);
if (!empty($the_content)) {
    echo $the_content;
}

Check if the_content has content using a custom function

Call the custom function inside the loop or with a post ID:

function mytheme_has_content($post = 0) {
    $post = get_post($post);
    return (!empty(apply_filters('the_content', $post->post_content)));
}

// Template inside the loop
if ($customQuery->have_posts()) {
    while ($customQuery->have_posts()) {
        $customQuery->the_post();
        $the_content = apply_filters('the_content', get_the_content());
        if (!empty($the_content)) {
            echo '<div class="content">' . $the_content . '</div>';
        }
    }
    wp_reset_postdata();
}

Tagged in

Leave a Comment

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