我正在尝试向我的站点添加一个函数,该函数将计算贴在帖子上的图像数量,如果只有一个,则向其中任何一个添加一个类<img>
或到包含<a>
.
我想我已经很接近了,但还没有PHP语法技能来完成它。我破解的代码来源于该主题的各个线程,是:
/**
*
* Single-image posts will receive a separate class name
*
*/
add_filter( \'the_content\', \'single_image_content_filter\', 20 );
// Count images in post
function single_image_content_filter( $content ) {
$attachments = get_children(array(\'post_parent\'=>$post->ID));
$imgcount = count($attachments);
// If only one attachment, add a new CSS class
if ( $imgcount === 1 ) {
global $post;
$classes = \'single-img\'; // separated by spaces, e.g. \'img image-link\'
// check if there are already classes assigned to the anchor, and/or add one via $classes
if ( preg_match(\'/<a.*? class=".*?">/\', $content) ) {
$content = preg_replace(\'/(<a.*? class=".*?)(".*?>)/\', \'$1 \' . $classes . \'$2\', $content);
} else {
$content = preg_replace(\'/(<a.*?)>/\', \'$1 class="\' . $classes . \'" >\', $content);
}
return $content;
}
}