Wordpress image caption doesn't display correctly

470 Views Asked by At

I have a Wordpress page, in which my images appears on left and my text appears on right. The images fall down under the text when the page is loaded on mobile screen. I have a PHP code to achieve all of that, basically it switchs image and text places, and attributes left or right to each.

But since this is in place, I have trouble adding images' captions. When I want to add images' captions in my Wordpress admin, the caption doesn't come under the image but it comes up my text article (so, on the right part of the page). I guess my PHP code attributes automaticaly this place to every text.

I need the images' captions to be under my images, and I guess this has a lot to do with that PHP code you can see below. But I don't know how to fix that.

Here is my PHP:

<?php if (have_posts()):  ?>
  <div class="container">
    <?php while(have_posts()): the_post(); ?>
      <div class="row">
        <div id="content_post">
          <div class="col-lg-push-5 col-lg-6 col-md-push-6 col-md-6 col-sm-12 col-xs-12 ">      
            <?php 
              //get content from back office , filter imgs except featured img to place them later in  <div id='img_content_right'>
              $content2 = get_the_content();                    
              $removed_imgs = array();                 
              $content2 = preg_replace_callback('#(?!<img.+?id="featured_img".*?\/>)(<img.+? />)#',function($r) {
              global $removed_imgs;
              $removed_imgs[] = $r[1];
              return '';
              },$content2);

              //add filter to the_content to strip images except img_menu et featured_img          
              add_filter('the_content', 'strip_images',2);                    
              function strip_images($content){            
              $content=preg_replace('/(?!<img.+?id="img_menu".*?\/>)(?!<img.+?id="featured_img".*?\/>)<img.+?\/>/','',$content);                                  
              return $content;                            
              }
              the_content(); 
            ?>
          </div>
        </div> 
        <div class="col-lg-pull-6 col-lg-5 col-md-pull-6 col-md-6"> 
          <div id='img_content_right'>
            <?php       
            //append the images stripped from content
            foreach($removed_imgs as $img){
            echo $img; }  ?>
          </div> 
        </div>     
      </div>
    </div>  
  <?php endwhile; ?>
<?php endif; ?> 

1

There are 1 best solutions below

0
On

To appropriately handle the caption you need to get the attachment post object and then look at the post_excerpt.

There's a function in WordPress get_attached_media, which will list all of the images within a posts content. This be easier to iterate over then using regex to find the images.