Is it possible to handle a specific section of a post separately?

You can make use of featured images as suggested by @gmazzap in comments. This featured image will not be included in post content. However, if you already have your images included in post content, then you need to strip the post content down in two parts, as you’ve said in your question.

I have two functions, one that returns all the images (or any html tag content) from the content and one function that returns the text without the desired tag/images. Both of these functions uses DOMDocument

The first function get_content_without_tag() returns the content which has been stripped from images. There are two parameters

  • $html -> The text with images to be stripped, in this case, use apply_filters( 'the_content', get_the_content() ) to use the post content

  • $tag -> The name of the tag to strip out, in this case, ‘a’ as a tags hold images

Here is the function

function get_content_without_tag( $html, $tag )
{
    $dom = new DOMDocument;
    $dom->loadHTML( $html );

    $dom_x_path = new DOMXPath( $dom );
    while ($node = $dom_x_path->query( '//' . $tag )->item(0)) {
        $node->parentNode->removeChild( $node );
    }
    return $dom->saveHTML();
}

You would then use this in place of the_content() where you would need to display text only, stripping out the complete <a/> tag in which the images are as follows

echo get_content_without_tag( apply_filters( 'the_content', get_the_content() ), 'a' )

The second function, get_tag_without_text() returns the content between the desired tag, in your case, images. The parameters are exactly the same as the first function. Here is the function

function get_tag_without_text( $html, $tag )
{
    $document = new DOMDocument();
    $document->loadHTML( $html );  

    $tags = [];
    $elements = $document->getElementsByTagName( $tag );
    if ( $elements ) {
        foreach ( $elements as $element ) {
            $tags[] = $document->saveHtml($element);
        }   
    }   
    return $tags;
}

This function returns an array of images should you use a tags, so, to display the first image, use the function as follow:

$image = get_tag_without_text( apply_filters( 'the_content', get_the_content() ), 'a' );
echo $image[0];

Just one final tip on your code, move your call the side bar outside your loop. It should go just above the call to the footer

Leave a Comment