问题
I want to add a div around every image that is posted on my wordpress blog post. How can I do it?
(For the curious ones, I'm attempting to pop out some share buttons whenever a user hovers over an image).
回答1:
Add the following snippet of code into your functions.php file:
add_filter( 'image_send_to_editor', 'wp_image_wrap_init', 10, 8 );
function wp_image_wrap_init( $html, $id, $caption, $title, $align, $url, $size, $alt ) {
return '<div id="wp-image-wrap-'. $id .'" class="wp-image-wrap">'. $html .'</div>';
}
回答2:
So this solved everything :) ! Thank you guys for your help here. I hope it will be useful to others.
function breezer_addDivToImage( $content ) {
// A regular expression of what to look for.
$pattern = '/(<img([^>]*)>)/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$the_url = the_permalink();
$replacement = '<div class="imgWrap">
$1
<div class="imgDescription">
<div class="theShareLinks">
<img src="http://localhost/mysite/wp-content/uploads/2014/08/dfc2.png" />
<a href="http://twitter.com/share?text=&url='.get_the_permalink() .'" class="img-twitter" title="Share on Twitter" target="_blank"></a>
<a href="http://www.facebook.com/sharer.php?u='.get_the_permalink() .'?" class="img-facebook" title="Share on Facebook" target="_blank" onclick="window.open(this.href, \'newwin\', \'width=500, height=200\'); return false;" ></a>
<a href="https://plus.google.com/share?url='.get_the_permalink() .'" class="img-google" title="Share on Google" target="_blank"></a>
</div>
</div>
</div>';
// run preg_replace() on the $content
$content = preg_replace( $pattern, $replacement, $content );
// return the processed content
return $content;
}
add_filter( 'the_content', 'breezer_addDivToImage' );
回答3:
If it's as simple as you make seem, just switch to the text editor, or disable the visual editor, and add the div around every image you insert. Give them all the same class, and then add your style for that class in your stylesheet.
-- Or, if you want to apply this to all kinds of pages on your Wordpress installation (Pages, Posts, Archives, Categories etc): --
Dive into the FTP, and start having a look in your themes folders and files.
You've got different pages for different views. attachment.php, page.php etc. Depending on which view you want to change, these files will include a line that may look similar to this:
<p class="attachment">
<a href="<?php echo wp_get_attachment_url( $post->ID ); ?>" title="<?php the_title(); ?>" rel="attachment">
<img src="<?php echo $att_image[0]; ?>" width="<?php echo $att_image[1]; ?>" height="<?php echo $att_image[2]; ?>" class="attachment-medium" alt="<?php $post->post_excerpt; ?>" />
</a>
</p>
Or anywhere that mentions
<img src="<?php echo $att_image[0]; ?>" />
Just add a div around that, and add a styling rule in your stylesheet.
来源:https://stackoverflow.com/questions/25403001/how-do-i-add-a-div-around-each-wordpress-post-image