0

I'm looking to use the_content() on a particular page, but I want it to be surrounded with an <h1> instead of a <p>.

I've tried doing this:

$thisPagesContent = the_content();
echo '<h1' . $thisPagesContent . '</h1>';

This works, but it strips the <br> tag that I have in the content.

Any way around this?

Thanks

2

1 Answer 1

1

First you should use get_the_content() to assign the content to a variable (instead of the_content() which is meant to display it instead of returning it).

Then you will want to apply filters hooked to 'the_content' just like the_content() does (see the source).

Here is a revised version of your original code:

$thisPagesContent = get_the_content();
$thisPagesContent = apply_filters( 'the_content', $thisPagesContent );
$thisPagesContent = str_replace( ']]>', ']]&gt;', $thisPagesContent );
echo '<h1>' . $thisPagesContent . '</h1>';

An alternative way to approach it would be to create a filter in the functions.php file of your theme or child theme or in a plugin and hook it to 'the_content', with a conditional so that it only applies to the target page. On said page, you would then just call the_content() as normal and the filter would apply. This approach would more neatly separate content manipulation and presentation.

Example:

function wpst_304021_wrap_content_in_h1( $content ) {

    if ( is_page( '123' ) ) { // Assuming your "target" page's ID is '123', you can also use the page's title or slug or another conditional altogether.
        return '<h1>' . $content . '</h1>';
    }

   return $content;
}
add_filter('the_content', 'wpst_304021_wrap_content_in_h1');

As an aside, I do hope you have a specific use case with a good reason do to this, as wrapping the whole content of a post in a heading tag would be a terrible idea in most cases.

2
  • I tried these, the first wrapped the content in an <h1>, but the p was still inside of it. Commented May 20, 2018 at 17:23
  • If you additionally don't want any p tags to be included automatically, you'll need to disable wpautop, which one of the filters hooked to the_content. Adding remove_filter( 'the_content', 'wpautop' ); just before calling apply_filters (second line), should do the trick.
    – Iceable
    Commented May 20, 2018 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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