I recently added a caption to my image in WordPress and now there is an empty <p></p>
tag after <img>
tag. It broke my style.
Can anyone tell how to remove it?
Thanks for the help.
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIt is not a good practice to override the WordPress native functionality. Instead you can hide the empty elements using CSS
p:empty {
display: none;
}
This will the empty elements.
wpautop
:This is most likely from wpautop
. To fix that, first write the following CODE in your theme's functions.php
file:
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
If it doesn't solve the issue, that may mean <p></p>
got into your database or you have empty newline inside your [caption][/caption]
Shortcode. Go to the post & edit out the <p></p>
or empty new line
from WordPress editor's Text
mode.
That should solve your problem.
You may use CSS CODE to hide <p></p>
as this answer suggested. However, with that method, it'll still be in your HTML & there's no point in creating it and then hiding it entirely with CSS. It's better to remove it in that case with the above CODE.
However, if you want to keep wpautop
for some reason (may be you are using it for formatting somewhere else in the site), then you may target only the <p></p>
tags within the captions with the following CSS:
.wp-caption > p:empty {
display: none;
}
This will keep the formatting of wpautop
elsewhere in your site and at the same time solve the display problem for the captions.
You can also remove this using str_replace
to replace the p tags with the_content
filter:
function wpse256087_content_filter($content) {
$content = str_replace( '<p></p>', '', $content );
return $content;
}
add_filter( 'the_content', 'wpse256087_content_filter' );
You can do this on the do_shortcode_tag
hook.
function remove_empty_wp_caption_text($output, $tag) {
if ($tag === 'caption') {
$output = str_replace('<p class="wp-caption-text"> </p>', '', $output);
}
return $output;
}
add_filter('do_shortcode_tag', 'remove_empty_wp_caption_text', 10, 2);
What's nice about this approach is that the function won't be ran unless the [caption]
shortcode is called.
<p>
tag is inside the<div>
tag of the attachment itself so its probably because of your theme. Perhaps it's reserved for the Description field? What's the output when you add a description to your image?<p>
tag or altering the attachments.