如何在wordpress中的函数下添加wordpress循环

I want to add google adds in my single news post. I used below code for this but when I put wordpress loop page not working. How can I solve this problem. I want to get image from custom post. here I attached what I do in my function.php

function prefix_insert_post_ads( $content ) {
        //The last condition here ensures that ads are only added to posts
        if ( is_single() && !is_admin() && get_post_type() === 'post' ) {
            return prefix_insert_ads( $content );
        }

        return $content;
    }

    function prefix_insert_ads( $content ) {

        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
        foreach ($paragraphs as $index => $paragraph) {
            $paragraphs[$index] .= $closing_p;

            if ( in_array($index, array(3)) ) {
                $the_query = new WP_Query( array( 'post_type' =>'advertisement','orderby'=>'post_date','order'=>'desc','posts_per_page' => '2',$i=-1, 'offset'=> 1) );
         if ( have_posts())   : while ( $the_query->have_posts() ) : $the_query->the_post();



                $thumbnail_id = get_post_thumbnail_id(); 
                $thumbnail_url = wp_get_attachment_image_src( $thumbnail_id, 'thumbnail-size', true );
                $thumbnail_meta = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true); 


                //Replace the html here with a valid version of your ad code
                $paragraphs[$index] .= '<div class="hidden-lg"><img class="img img-responsive center-img" src="http://www.test.oddly.co/hospitality/wp-content/uploads/2019/02/ad4.jpg" height="" width="300px" alt=""></div>';

endwhile;
endif; wp_reset_Query();

            }
            else if ( in_array($index, array(5)) ) {
                //Replace the html here with a valid version of your ad code
                $paragraphs[$index] .= '<div class="hidden-lg"><img class="img img-responsive center-img" src="http://www.test.oddly.co/hospitality/wp-content/uploads/2019/02/ad4.jpg" height="" width="300px" alt=""></div>';
            }
            else if ( in_array($index, array(9)) ) {
                //Replace the html here with a valid version of your ad code
                $paragraphs[$index] .= '<div class="hidden-lg"><img class="img img-responsive center-img" src="http://www.test.oddly.co/hospitality/wp-content/uploads/2019/02/ad4.jpg" height="" width="300px" alt=""></div>';
            }



        }

        return implode( '', $paragraphs );
    }