UPDATED: Insert content within Wordress’ php the_content


I’m a long time beginner in WordPress theming (i do bits here and there for myself) and have a question. I run a very large website and i’m trying to redesign it (responsive etc) and have run into a problem…

Basically my content is text then a video or image underneath in every post. I am trying to position my tags underneath the text but before the media so it goes:-

  1. header
  2. text
  3. tags
  4. media

My question is would it be possible to do this.. somehow slip the tags in after the paragraphs but before the media?

Just incase it matters i have this in my Functions file to help control the embedded videos..

 /** embed modifyer */

function video_embed_html( $html ) { 
    return '<div class="innerpostvideo">' . $html . '</div>'; 
add_filter( 'embed_oembed_html', 'video_embed_html', 10 );

Thanks in advance!!

PS i can’t edit every post to do this.. i have almost 10,000 posts

EDIT: I should mention the images are also links.

UPDATED: User Pat J Came up with a solution which was great but had a couple of problems. On the image post it works almost as intended except it prints the html inside the "a" tag of the img. On the Video post, it’s acting kind of strange, it goes in this order:- 1, Paragraphs 2, video 3, My Custom HTML 4, Paragraphs repeated 5, Video Repeated So it’s printing the content twice. His code is below:-

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>' .
    return $content;
Jason 3 months 0 Answers 11 views 0

Leave an answer