Remove P tags from images

时间:2015-07-20 作者:agon024

我使用的是WordPress 4.2.2,每次我向wysiwyg添加图像时,它都会将输出的图像包装在段落标记中。我需要去掉这些标签。我在网上找到的所有东西都是从2011年开始的,而且似乎都不起作用。

我试着把东西放在函数中。php类:

function filter_ptags_on_images($content){
  return preg_replace(\'/<p>\\s*(<a .*>)?\\s*(<img .* \\/>)\\s*(<\\/a>)?\\s*<\\/p>/iU\', \'\\1\\2\\3\', $content);
}
add_filter(\'the_content\', \'filter_ptags_on_images\');
似乎什么都没用。我怎样才能做到这一点。

顺便说一句,我使用的是ACF Pro的wysiwyg和JointsWP入门主题,如果这有什么不同,我的图像不会包装在链接标签中。

2 个回复
最合适的回答,由SO网友:Bryan Willis 整理而成

1) Filter wpautop() with ACF:

function filter_ptags_on_images($content) {
    $content = preg_replace(\'/<p>\\s*(<a .*>)?\\s*(<img .* \\/>)\\s*(<\\/a>)?\\s*<\\/p>/iU\', \'\\1\\2\\3\', $content);
    return preg_replace(\'/<p>\\s*(<iframe .*>*.<\\/iframe>)\\s*<\\/p>/iU\', \'\\1\', $content);
}
add_filter(\'acf_the_content\', \'filter_ptags_on_images\');
add_filter(\'the_content\', \'filter_ptags_on_images\');
如果两者都有,请尝试在add\\u筛选器上使用稍后的优先级进行检查。有可能主题、插件或acf正在覆盖您。。。。

add_filter(\'acf_the_content\', \'filter_ptags_on_images\', 9999);
add_filter(\'the_content\', \'filter_ptags_on_images\', 9999);

2) Edit wpautop():

<?php
remove_filter( \'the_content\', \'wpautop\' );
add_filter( \'the_content\', \'custom_wpautop\' );
function custom_wpautop() {
 // copy wpautop() code at https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L373 and add img to the $allblocks variable
}
3) This above is a lot of code for one task however. Consider trying this:https://wordpress.org/plugins/preserved-html-editor-markup-plus

4) You could try this although not as good as the method you\'re trying to accomplish since this one is done with javascript.

<script type="text/javascript">
jQuery(document).ready(function($){
    $(\'p > img\').unwrap();
});
</script>

5) if it\'s just the styling that\'s messing things up and you don\'t care about the markup:

<style type="text/css">
p > img {
    margin: 0 !important;
}
</style>

SO网友:Nuno Sarmento

我使用acf\\u the\\u内容过滤器来preg\\u替换p标记。下面的代码将替换p标记并将图像包装在div中

/**
 * Remove P tags from images
 */
function ns_img_unautop($custom_content) {
   $custom_content = preg_replace(\'/<p>\\\\s*?(<a .*?><img.*?><\\\\/a>|<img.*?>)?\\\\s*<\\\\/p>/s\', \'<div class="figure">$1</div>\', $custom_content);
   return $custom_content;
}
add_filter( \'acf_the_content\', \'ns_img_unautop\', 30 );

结束

相关推荐

Search tags in CPTs

我似乎不知道如何在wordpress搜索中包含标签。例如,如果我搜索“apple”,我希望在标题或内容中返回带有“apple”的帖子(默认wordpress功能)as well as 包含标签“apple”的帖子;当我添加\'tag\' => $keyword 行到WP\\u查询中,然后每次搜索都没有结果。$keyword = get_search_query(); $args = array( \'post_type\' => array(\'case_studie