简体   繁体   中英

Wordpress: How to add a caption right-aligned to the edge of the image

So how do I align an image caption under an image tag to it's right hand edge?

Tried using div but obviously that's not allowed in wp.

What alternative css/tags do I need to use?

Does this not work?

.wp-caption p.wp-caption-text { text-align:right; }

I came up with a way to specify alignment on a per-caption basis.

Basically, I copied the caption shortcode from the media.php and made it into my own custom function which accepts a "captionalign" argument.

To use, paste the below code into your theme's "function.php" file - this will allow you to specify an option in your caption tag named captionalign. By setting this to right, left, or center, you can specify a per-caption text alignment. Leaving out the attribute will have the caption default to whatever you have your default alignment as.

An example of this in use:

[caption align="aligncenter" width="300" caption="My caption" captionalign="right"]
<a href="http://www.myawesomeblog.com/wp-content/uploads/2010/05/image.jpg">
<img title="My image" src="http://www.myawesomeblog.com/wp-content/uploads/2010/05/image.jpg-300x216.jpg" alt="My image" width="300" height="216" />
</a>
[/caption]

And here is the function:

add_shortcode('wp_caption', 'custom_img_caption_shortcode');
add_shortcode('caption', 'custom_img_caption_shortcode');

/**
 * The Caption shortcode.
 *
 * Allows a plugin to replace the content that would otherwise be returned. The
 * filter is 'img_caption_shortcode' and passes an empty string, the attr
 * parameter and the content parameter values.
 *
 * The supported attributes for the shortcode are 'id', 'align', 'width', and
 * 'caption'.
 *
 * @since 2.6.0
 *
 * @param array $attr Attributes attributed to the shortcode.
 * @param string $content Optional. Shortcode content.
 * @return string
 */
function custom_img_caption_shortcode($attr, $content = null) {

// Allow plugins/themes to override the default caption template.
$output = apply_filters('img_caption_shortcode', '', $attr, $content);
if ( $output != '' )
    return $output;

extract(shortcode_atts(array(
    'id'    => '',
    'align' => 'alignnone',
    'width' => '',
    'caption' => '',
    'captionalign' => ''
), $attr));

if ( 1 > (int) $width || empty($caption) )
    return $content;

if ( $id ) $id = 'id="' . esc_attr($id) . '" ';

return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
. do_shortcode( $content ) . '<p class="wp-caption-text" style="text-align:' . $captionalign . '">' . $caption . '</p></div>';
}

Hope that helps someone!

在Wordpress社区网站论坛上也被问到 ,没有回应,因此推测这不是2.2.1的功能

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM