Filter captioned images to include source link
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Filter captioned images to include source link | |
* | |
* @link https://core.trac.wordpress.org/browser/trunk/src/wp-includes/media.php (img_caption_shortcode) | |
* | |
*/ | |
add_filter( 'img_caption_shortcode', 'ac_add_sources_captioned', 10, 3 ); | |
function ac_add_sources_captioned( $empty, $attr, $content ) { | |
$atts = shortcode_atts( array( | |
'id' => '', | |
'align' => 'alignnone', | |
'width' => '', | |
'caption' => '', | |
'class' => '', | |
), $attr, 'caption' ); | |
$post_id = explode( '_', esc_attr( $atts['id'] ) ); | |
$source_url = get_post_meta( $post_id[1], '_wp_attachment_source_url', true ); | |
// We have a source | |
if ( ! empty( $source_url ) ) { | |
// Source name | |
$source_name = get_post_meta( $post_id[1], '_wp_attachment_source_name', true ); | |
if ( empty( $source_name ) ) { | |
$parsed_url = parse_url( $source_url ); | |
$source_name = str_replace( 'www.', '', $parsed_url['host'] ); | |
} | |
// Code from /wp-includes/media.php | |
$atts['width'] = (int) $atts['width']; | |
if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) { | |
return $content; | |
} | |
if ( ! empty( $atts['id'] ) ) { | |
$atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" '; | |
} | |
$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] ); | |
// Return output along with source | |
return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '"><span class="image-wrap">' . do_shortcode( $content ) . '<span class="source"><a href="' . esc_url( $source_url ) . '" target="_blank">' . $source_name . '</a></span></span><figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>'; | |
} | |
// No source | |
else { | |
return ''; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment