Insert content above an embedded video inside Wordress’ php the_content

I came up with this, which seems to work.

Notes:

  • It adds the custom HTML before the very first image / media embed in a post’s content; if there are more than one image / video, it’ll only place the custom HTML once
  • It requires the innerpostvideo div you mentioned in your question

You can add the code to your active theme’s functions.php file, or write a custom plugin.

add_filter( 'the_content', 'wpse377076_insert_above_image', 20 );
/**
 * Inserts some HTML above a piece of media (image or video).
 *
 * @param  string $content The post/page content.
 * @return string          The filtered content.
 */
function wpse377076_insert_above_image( $content ) {
    // Checks for <img tags in the content.
    if ( false !== strpos( $content, '<img' ) || false !== strpos( $content, '<div class="innerpostvideo' ) ) {
        // Only inserts above the first image/video.
        $image_position = strpos( $content, '<img' );
        $video_position = strpos( $content, '<div class="innerpostvideo' );
        // Gets the position of the first item.
        $position = 0; 
        if ( false !== $image_position ) {
            $position = $image_position;
        }
        if ( false !== $video_position && $video_position < $image_position ) {
            $position = $video_position;
        }
        $content_up_to_first_media = substr( $content, 0, $position-1 );
        $content_after_first_media = substr( $content, $position );
        $content = 
            $content_up_to_first_media .
            '<div class="my-tags">My custom HTML</div>' .
            $content_after_first_media;
    }
    return $content;
}