我在functions.php中有以下代码,它将文本包装在<class="row">
和<class ="col-md-10">
的Wordpress帖子中,并保留图像的完整/未包装
的functions.php
function sr_wrap_content_in_div( $content )
{
$contents = explode("<img", $content);
foreach($contents as $content)
{
$before_tag = strstr($content, '/>', true);
$after_tag = strstr($content, '/>');
if( $before_tag == '' && $after_tag == '' )
{
echo '<div class="content-wrap row"><div class="col-md-10 col-md-push-1">'; // change it later if you need to
echo $content;
echo '</div></div>';
} else if( $after_tag == '/> ' )
{
echo '<img';
echo $before_tag;
echo '/>';
} else
{
echo '<img';
echo $before_tag;
echo '/>';
echo '<div class="content-wrap row"><div class="col-md-10 col-md-push-1">'; // change here too.
echo substr($after_tag, 2);
echo '</div></div>';
}
}
}
add_filter( 'the_content', 'sr_wrap_content_in_div' );
代码可以工作,但它会在这些类中包装空白区域(在图像之间等)。这意味着我无法将margin css应用于.content-wrap
,因为它会在空格中产生间隙。
编辑:
示例输出(有问题)
<div class="content-wrap row">
<div class="col-md-10 col-md-push-1">
<p>content ... </p>
</div>
</div>
<img></img>
<div class="content-wrap row">
<div class="col-md-10 col-md-push-1">
</div>
</div>
<img></img>
etc
答案 0 :(得分:1)
要删除空白空间,请尝试使用以下代码而不是以上共享。
function sr_wrap_content_in_div( $content ) {
$contents = explode("<img", $content);
foreach($contents as $content) {
$before_tag = strstr($content, '/>', true);
$after_tag = strstr($content, '/>');
if( $before_tag == '' && $after_tag == '' ) {
echo '<div class="content-wrap row"><div class="col-md-10 col-md-push-1">' . $content . '</div></div>'; // change it later if you need to
} else if( $after_tag == '/> ' ) {
echo '<img' . $before_tag . '/>';
} else {
echo '<img' . $before_tag . '/>' . '<div class="content-wrap row"><div class="col-md-10 col-md-push-1">' . substr($after_tag, 2) . '</div></div>'; // change here too.
}
}
}
add_filter( 'the_content', 'sr_wrap_content_in_div' );