Filter non-captioned images to include source link
<?php | |
/** | |
* Filter non-captioned images to include source link | |
* | |
*/ | |
add_filter( 'the_content', 'ac_add_sources_non_captioned', 11 ); | |
function ac_add_sources_non_captioned( $content ) { | |
if ( is_singular( array( 'post', ) ) ) { | |
$search = $replace = array(); | |
// Match non-captioned images | |
if ( preg_match_all( '/(<p[^>]*?>\s*)((?:<a [^>]+>\s*)?<img [^>]+)wp-image-(\d+)([^>]+>(?:\s*<\/a>)?)/', $content, $matches, PREG_SET_ORDER ) ) { | |
foreach ( $matches as $match ) { | |
$source_url = get_post_meta( $match[3], '_wp_attachment_source_url', true ); | |
// We have a source | |
if ( ! empty( $source_url ) ) { | |
// Source name | |
$source_name = get_post_meta( $match[3], '_wp_attachment_source_name', true ); | |
if ( empty( $source_name ) ) { | |
$parsed_url = parse_url( $source_url ); | |
$source_name = str_replace( 'www.', '', $parsed_url['host'] ); | |
} | |
// Alignment | |
if ( false !== ( strpos( $match[2], 'alignnone' ) || strpos( $match[4], 'alignnone' ) ) ) { | |
$alignment = 'none'; | |
$style = ''; | |
} | |
elseif ( false !== ( strpos( $match[2], 'alignright' ) || strpos( $match[4], 'alignright' ) ) ) { | |
$alignment = 'right'; | |
$style = ''; | |
} | |
elseif ( false !== ( strpos( $match[2], 'alignleft' ) || strpos( $match[4], 'alignleft' ) ) ) { | |
$alignment = 'left'; | |
$style = ''; | |
} | |
elseif ( false !== ( strpos( $match[2], 'aligncenter' ) || strpos( $match[4], 'aligncenter' ) ) ) { | |
$alignment = 'center'; | |
// get width! | |
if ( preg_match( '/width="(\d+)"/', $match[4], $width ) ) { | |
$style = ' style="width:' . $width[1] . 'px;"'; | |
} | |
else { | |
$style = ''; | |
} | |
} | |
else { | |
continue; | |
} | |
// Build search and replace arrays | |
$search[] = '%' . preg_quote( $match[1] . $match[2] . 'wp-image-' . $match[3] . $match[4], '%' ) . '%'; | |
$replace[] = $match[1] . '<span class="image-wrap image-wrap-' . $alignment . '"' . $style . '>' . $match[2] . 'wp-image-' . $match[3] . $match[4] . '<span class="source"><a href="' . esc_url( $source_url ) . '" target="_blank">' . $source_name . '</a></span></span>'; | |
} | |
} | |
} | |
// preg_replace | |
if ( ! empty ( $search ) ) { | |
$content = preg_replace( $search, $replace, $content ); | |
} | |
} | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment