How to convert Wordpress caption tag to html div tag

1.8k views Asked by At

I converted a webiste from Wordpress and I some of the posts have a caption tag as the following:

[caption id="attachment_666" align="alignleft" width="316"]
    <img class="wp-image-92692" src="img" width="316"  alt="fitbit-yoga-lady.png" height="210">   
    text
[/caption]

I would like to catch all of these captions and convert it to the following

<div id="attachment_666" style="width: 326px" class="wp-caption alignleft">
  <img class="wp-image-92692" src="img" alt="fitbit-yoga-lady.png" width="316" height="210">
  <p class="caption">text</p>
</div>

2

There are 2 answers

1
Steven Doggart On BEST ANSWER

Well, given the exact text that you provided, the following should work.

Search Pattern:

\[caption([^\]]+)align="([^"]+)"\s+width="(\d+)"\](\s*\<img[^>]+>)\s*(.*?)\s*\[\/caption\]

Replacement:

<div\1style="width: \3px" class="wp-caption \2">\4
    <p class="caption">\5</p>
</div>

See the demo.

Depending on how tolerant of variations in the input it needs to be, you may need to adjust it from there, but that should at least get you started.

Here's an example of how this could be done with preg_replace:

function convert_caption($content) 
{ 
    return preg_replace(
        '/\[caption([^\]]+)align="([^"]+)"\s+width="(\d+)"\](\s*\<img[^>]+>)\s*(.*?)\s*\[\/caption\]/i', 
        '<div\1style="width: \3px" class="wp-caption \2">\4<p class="caption">\5</p></div>', 
        $content); 
}
0
Andrew Hosgood On

I'm doing this blindly on my phone, but I think you can use the following two regular expressions, one for the opening tag and another for the closing:

Find: \[caption([^\]])\] Replace: <div$1>

Find: \[/\caption\] Replace: </div>